I am currently using the pragmatic screencast on Objective-C to help me program in objective-c. I have a background in Java and C++, but I am having a very difficult time getting used to everything in Ob开发者_开发问答jective(Mostly because I am not comfortable with the syntax). Below is the error I am receiving with all the code. I am also getting a warning in movie.m class as well: Wirtable atomic property 'title' cannot be pair a synthesized setter/getter with a user defined setter/getter
thanks for your help.
I am receive this error
Current language: auto; currently objective-c
warning: Couldn't find class validation function, calling methods on uninitialized objects may deadlock your program.
Program received signal: “EXC_BAD_ACCESS”.
I ran it through the debugger and the address of movie in the code below is in red
main.m
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Movie *movie = [[Movie alloc] initWithTitle:@"iron man"
andRating:5
andYear:2008];
[movie play];
NSLog(@"our movie is %@", movie);
[pool drain];
return 0;}
Movie.h
interface Movie : NSObject {
NSString *title;
int rating;
int year;
}
- (id)initWithTitle:(NSString *)newTitle
andRating:(int)newRating
andYear:(int) year;
@property(assign) NSString *title;
@property(assign) int rating;
@property(assign) int year;
-(void) play;
@end
Movie.m
#import "Movie.h"
@implementation Movie
@synthesize title;
@synthesize rating;
@synthesize year;
-(id)initWithTitle:(NSString *)newTitle
andRating:(int)newRating
andYear:(int)newYear;
{
self = [super init];
if(nil != self){
self.title = newTitle;
self.rating = newRating;
self.year = newYear;
}
return self;
}
-(NSString *) description{
NSString *oldDescription = [super description];
return [NSString stringWithFormat: @"%@ title =%@, rating =%d year=%@",
oldDescription, self.title, self.rating, self.year];
}
- (void)setTitle:(NSString *)newTitle {
title = [newTitle capitalizedString];
}
-(void) play {
NSLog(@"Playing %@", self);
}
You use year=%@
when it should be year=%d
.
Some more random thoughts:
You should retain or better even copy the title instead of assigning it.
The init method should be named
-(id)initWithTitle:(NSString *)aTitle
rating:(int)aRating
year:(int)aYear;
Don't forget a dealloc
method then.
Your title
property is an object type and so should in generally be either retain
or copy
-- in the case of NSString
properties, it is traditional to use copy
to avoid issues when you're passed an NSMutableString
instead.
@property (copy) NSString* title;
Since you explicitly define the setter, you then need to implement this policy yourself, something like this:
- (void)setTitle:(NSString *)newTitle
{
[title release];
title = [[newTitle capitalizedString] copy];
}
You'll also need to include a dealloc
method to clean up:
- (void) dealloc
{
[title release];
[super dealloc];
}
精彩评论