gpt4 book ai didi

objective-c - iOS 无法识别的选择器发送到实例 - 添加 NSDictionary 到 NSMutableArray

转载 作者:塔克拉玛干 更新时间:2023-11-01 19:14:20 26 4
gpt4 key购买 nike

为大量代码道歉,但人们通常最终还是会要求很多代码。

尝试将 NSDictionary 添加到 NSMutableArray 时出现以下错误

2011-09-22 18:52:54.153 NPT[4788:1603] -[__NSArrayI addObject:]: unrecognized selector sent to instance 0x72f1280
2011-09-22 18:52:54.154 NPT[4788:1603] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI addObject:]: unrecognized selector sent to instance 0x72f1280'
Call stack at first throw:
(
0 CoreFoundation 0x028e5919 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x02a335de objc_exception_throw + 47
2 CoreFoundation 0x028e742b -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x02857116 ___forwarding___ + 966
4 CoreFoundation 0x02856cd2 _CF_forwarding_prep_0 + 50
5 NPT 0x00007197 -[Search addPlateToFinals:withSubCount:] + 791
6 NPT 0x0000626f -[Search makeNumberedPlatesForPass:] + 1132
7 NPT 0x0000401f __-[FirstViewController improveSearch]_block_invoke_1 + 173
8 libSystem.B.dylib 0x96f02a24 _dispatch_call_block_and_release + 16
9 libSystem.B.dylib 0x96ef4cf2 _dispatch_worker_thread2 + 228
10 libSystem.B.dylib 0x96ef4781 _pthread_wqthread + 390
11 libSystem.B.dylib 0x96ef45c6 start_wqthread + 30
)
terminate called after throwing an instance of 'NSException'

据我从堆栈跟踪和使用换行符可以看出,这是抛出错误的代码:

NSDictionary *dPlateToAdd = [NSDictionary dictionaryWithObjects:objects forKeys:keys];       
[self.aFinals addObject:dPlateToAdd];

self.aFinals在接口(interface)中decalar,然后作为属性,然后合成然后初始化如下:

Search.h

@interface Search : NSObject {
...
NSMutableArray *aFinals;
...

}
...
@property (nonatomic, retain) NSMutableArray *aFinals;
...
@end

Search.m

...
@synthesize aFinals;
...

-(id)initWithTerm:(NSString *)thisTerm andPrevResults:(NSMutableArray *)aPrevResults {

...
self.aFinals = [aPrevResults copy];
...
}

传入的 aPrevResults 是先前已发布的搜索对象的属性,但已被复制到 View Controller 的属性,并发送回新的搜索对象,以添加更多结果。

抛出错误的行在第一次运行时运行良好,但仅在第二次运行时出现问题,此时我重用现在为 aPrevResults 的数组。

我做错了什么?这些都有意义吗?

最佳答案

-copy 返回不可变对象(immutable对象),即使您在可变数组上调用它也是如此。要获取可变副本,您必须调用 mutableCopy 方法:

-(id)initWithTerm:(NSString *)thisTerm andPrevResults:(NSMutableArray *)aPrevResults {

...
self.aFinals = [aPrevResults mutableCopy];
...
}

此外,由于您使用的是保留属性,因此您需要补偿额外的增量以保留副本上发生的计数:

 self.aFinals = [[aPrevResults mutableCopy] autorelease];

或者,可能是使用便利类方法的最佳和最干净的解决方案:

 self.aFinals = [NSMutableArray arrayWithArray:aPrevResults];

关于objective-c - iOS 无法识别的选择器发送到实例 - 添加 NSDictionary 到 NSMutableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7520424/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com