對不起,我是新來的iOS開發,這一天,我遇到了一個奇怪的問題: 當我從自定義對象刪除對象時,它總是返回崩潰:NSMutableArray裏的removeObject崩潰
原因:「 - [ __NSArrayI removeLastObject]:無法識別的選擇發送到實例
以下代碼:
@interface Base : NSObject
@property (nonatomic, assign) BOOL isFinish;
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *subTitle;
@property (nonatomic, strong) NSString *tagURL;
@property (nonatomic, assign) NSInteger taskScore;
@property (nonatomic, assign) BOOL inProgress;
@property (nonatomic, assign) NSInteger nowTime;
@property (nonatomic, assign) NSInteger totalTime;
@end
然後我使用另一個類:
@property (nonatomic, strong) NSMutableArray *arr1;
@property (nonatomic, copy) NSMutableArray *arr2;
_arr1 = [[NSMutableArray alloc] init];
for (int i = 0; i < 10; i++) {
Base *b = [[Base alloc] init];
b.title = [[NSString alloc] initWithFormat:@"%d", i];
[_arr1 addObject:b];
}
self.arr2 = [_arr1 copy];// 001, I tried copy or mutable copy
[_arr2 removeLastObject]; //it always crash in here!!
所以我通過一些參考一下,有的告訴我必須符合nscopying或nsmutablecopying協議
所以我添加一些方法在基類@implementation
- (id)copyWithZone:(struct _NSZone *)zone
{
Base *copy = [[[self class] allocWithZone:zone] init];
if (copy) {
[copy setIsFinish:[self isFinished]];
[copy setTitle:[self title]];
[copy setSubTitle:[self subTitle]];
[copy setTagURL:[self tagURL]];
[copy setTaskScore:[self taskScore]];
[copy setInProgress:[self inProgress]];
[copy setNowTime:[self nowTime]];
[copy setTotalTime:[self totalTime]];
}
return copy;
}
但不起作用,有人能幫助我嗎?
如果你(OP)想知道如何解決你的問題 - 你可以改變'@property(nonatomic,copy)NSMutableArray * arr2;'以'@property(nonatomic,strong)NSMutableArray * arr2;'爲例。格納赫的解釋是正確的。 – cania
...並返回到使用可變副本'self.arr2 = [_arr1 mutableCopy];' – vacawama
@cania我想深拷貝.. – passol