实现类时出现Objective-C错误



我有这个类

#import <Foundation/Foundation.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

实现文件是这样的:

#import "SubscriptionArray.h"
@implementation SubscriptionArray
@synthesize title,source,htmlUrl;
-(void)dealloc{
    [title release];
    [source release];
    [htmlUrl release];
}
@end

当我像本例中那样使用类时,我会得到一个EXEC_BAD_ACCESS错误:

  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];

        }

有人能帮我吗?P.S.订阅是NSMutableArray

您需要分配SubscriptionArray对象,如下所示:SubscriptionArray *add = [[SubscriptionArray alloc] init];

因此,你的for循环看起来像这样:

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];
}

您需要初始化SubscriptionArray。即

SubscriptionArray *add = [SubscriptionArray new];

最新更新