簡體   English   中英

為什么會出現“無法識別的選擇器”錯誤?

[英]Why am I getting “unrecognized selector” errors?

我試圖自學目標c。 我曾經(〜10yr年前)對c ++相當滿意,所以我認為這應該不太難,但是經過python和各種數學編程語言的多年,我對指針等的使用還是相當生銹,我認為這是可能是什么原因造成的。

無論如何,我一直在文檔中肯定存在的方法中出現無法識別的選擇器錯誤,並且xcode的調試輸出(我不太熟悉,所以也許這是錯誤的)表明這些對象已初始化。 我試圖使以下示例盡可能小。 這是我寫的一門課:

// Graph.h

#import <Foundation/Foundation.h>

@interface Graph : NSObject

@property NSMutableSet *myObjects;
- (id)initWithNumElements:(int)total;
- (NSMutableSet *)addOneMore:(NSMutableSet *)vertices;
- (NSMutableSet *)addTo:(NSMutableSet *)R from:(NSMutableSet *)P;

@end

它的實現:

// Graph.m

#import "Graph.h"

@implementation Graph

// Put numbers 0, ..., total - 1 into the objects of self
- (id)initWithNumElements:(int)total {
    self = [super init];
    if (self) {
        NSMutableSet *objects = [[NSMutableSet alloc] init];
        for (int i=0; i<total; i++) {
            [objects addObject:[NSNumber numberWithInt:i]];
        }
        _myObjects = objects;
    }
    return self;
}

// If possible, add one of the objects of self to set
- (NSMutableSet *)addOneMore:(NSMutableSet *)set {
    NSMutableSet *allObjects = [self.myObjects copy];
    for (id elt in set) {
        [allObjects removeObject:elt];
    }
    //[allObjects minusSet:set];
    return [self addTo:[set copy] from:allObjects];
}

// If possible, add one object from P to R
- (NSMutableSet *)addTo:(NSMutableSet *)R from:(NSMutableSet *)P {
    if ([P count] == 0) {
        return R;
    }
    id v = [P anyObject];
    [R addObject:v];
    return R;
}

@end

我正在用以下代碼對其進行測試:

// main.m

#import <Foundation/Foundation.h>
#import "Graph.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Graph *G = [[Graph alloc] initWithNumElements:6];
        NSMutableSet *results = [G addOneMore:[[NSMutableSet alloc] init]];
        NSLog(@"%@", results);
    }
    return 0;
}

(我從邏輯上知道,這段代碼沒有任何意義。從曾經只具有少量意義的事物簡化為愚蠢。)

我得到錯誤

2014-10-27 11:19:14.936 Test[1469:303] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSSetI addObject:]: unrecognized selector sent to instance 0x100108a20'

xcode將我精確地指向“ [R addObject:v];”行。 但是調試人員說R是NSMutableSet *,而v是_NFCSNumber *,這是什么問題? 就我所知,那應該是有效的。

注釋掉的行“ // [allObjects minusSet:set];” 還生成了無法識別的選擇器錯誤,當我用上面的for循環替換它時不會發生。 據我所知,該行應該是有效的,我無法弄清楚這里出了什么問題。

addOneMore: ,該行

NSMutableSet *allObjects = [self.myObjects copy];

不會將可變集合分配給allObjects ,而是分配一個不變的NSSet 如果您想要可變的副本,則即使源容器(集合,數組,字典)是可變的變體,也需要使用mutableCopy copy返回不可變的實例。

您收到無法識別的選擇器錯誤,因為addObject:不是不可變集合的有效選擇器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM