【问题标题】:Objective-C error while implementing class?实现类时的Objective-C错误?
【发布时间】:2011-08-26 15:04:18
【问题描述】:

我有这门课

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


        }

有人可以帮助我吗? 附: Subscriptions 是一个 NSMutableArray

【问题讨论】:

    标签: iphone objective-c class implementation


    【解决方案1】:

    您需要像这样分配您的 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];
    }
    

    【讨论】:

    • 感谢您的回答,我更正了我的代码,现在我收到此错误:2011-08-26 17:14:18.102 NewsPad[1204:15203] *** 由于未捕获的异常而终止应用程序'NSInvalidArgumentException', reason: '-[__NSCFSet objectAtIndex:]: unrecognized selector sent to instance 0x7eb2cb0' 是什么意思?我该怎么办?
    • 您的元素变量似乎是指 NSSet 而不是 NSDictionary。要了解更多信息,我们需要查看定义 subs 的代码。
    • 在将add 添加到subscriptions 之后,您需要将[add release]; 放在循环的末尾。 @保罗
    • @Josh Yep 完全忘记了发布。将其添加到代码中:)
    【解决方案2】:

    您需要初始化您的 SubscriptionArray。即

    SubscriptionArray *add = [SubscriptionArray new];
    

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 2018-09-05
      • 1970-01-01
      • 2016-01-04
      • 1970-01-01
      • 1970-01-01
      • 2011-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多