Objective-C error while implementing class?
I have this class
#import <Foundation/F开发者_运维问答oundation.h>
@interface SubscriptionArray : NSObject{
NSString *title;
NSString *source;
NSString *htmlUrl;
}
@property (nonatomic,retain) NSString *title;
@property (nonatomic,retain) NSString *source;
@property (nonatomic,retain) NSString *htmlUrl;
@end
and the implementation file is this one:
#import "SubscriptionArray.h"
@implementation SubscriptionArray
@synthesize title,source,htmlUrl;
-(void)dealloc{
[title release];
[source release];
[htmlUrl release];
}
@end
When I use the class like in this example I get an EXEC_BAD_ACCESS error:
for (NSDictionary *element in subs){
SubscriptionArray *add;
add.title=[element objectForKey:@"title"]; //ERROR Happens at this line
add.source=[element objectForKey:@"htmlUrl"];
add.htmlUrl=[element objectForKey:@"id"];
[subscriptions addObject:add];
}
Can someone help me? P.S. Subscriptions is a NSMutableArray
You need to allocate your SubscriptionArray object like so: SubscriptionArray *add = [[SubscriptionArray alloc] init];
Your for loop will therefore look something like this:
for (NSDictionary *element in subs){
SubscriptionArray *add = [[SubscriptionArray alloc] init];
add.title=[element objectForKey:@"title"];
add.source=[element objectForKey:@"htmlUrl"];
add.htmlUrl=[element objectForKey:@"id"];
[subscriptions addObject:add];
[add release];
}
You need to initialize your SubscriptionArray. i.e.
SubscriptionArray *add = [SubscriptionArray new];
精彩评论