2013-07-20 33 views
-1

我正在嘗試使用makeObjectsPerformSelector方法。無法識別的選擇器設置爲實例

這是我的代碼。 我不明白爲什麼當我打電話makeObjectsPerformSelector有選uppercase:它沒有找到它...

#import "testAppViewController.h" 

@interface testAppViewController() 
- (void)uppercase; 

@property (nonatomic, strong) NSMutableArray *arrayTest; 

@end 

@implementation testAppViewController 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    [self start]; 
    // Do any additional setup after loading the view, typically from a nib. 
} 

- (void)uppercase 
{ 
    NSLog(@"---"); 
} 

- (void) start 
{ 
    self.arrayTest = [[NSMutableArray alloc] init]; 
    [self.arrayTest addObject:@"toto"]; 
    [self.arrayTest addObject:@"tata"]; 
    [self.arrayTest addObject:@"titi"]; 
    [self.arrayTest addObject:@"tutu"]; 


    for (NSString *s in self.arrayTest) 
     NSLog(@"1 - %@", s); 

    [self.arrayTest makeObjectsPerformSelector:@selector(uppercase)]; 

    for (NSString *s in self.arrayTest) 
     NSLog(@"2 - %@", s); 
} 
+2

難道是因爲有對'NSString'沒有這樣的方法? –

+0

@JoshCaswell我試了兩個它不會改變。 –

+0

咦?兩者是什麼? –

回答

2

makeObjectsPerformSelector呼籲數組中的對象的方法,而不是在你的類中的方法(這與數組內容實際上完全無關)。所以,錯誤是因爲NSString沒有uppercase方法(有或沒有參數)。

NSString的確有一個uppercaseString方法,但是這對你不會有任何幫助,因爲它會返回一個值,並且在使用makeObjectsPerformSelector時會丟失。

您可能想要使用其他方法來迭代數組內容以處理字符串。

+0

噢好吧,我完全誤解了makeObjectsPerformSelector實用程序。謝謝。 –

2

makeObjectsPerformSelector:會將指定的選擇器發送到數組中的每個對象。

所以你發送uppercase:到你陣列中的每個NSString。但是NSString沒有一個叫做uppercase:的方法。您在類中實施了您自己的類中的方法。

但即使你會調用uppercaseString(哪個NSString實現),因爲一個對象無法取代它本身將無法正常工作。

使這項工作的一種方法是在NSMutableString上的類別。

@interface NSMutableString (MBUpperCase) 
- (void)makeUpperCase; 
@end 

@implementation NSMutableString (MBUpperCase) 
- (void)makeUpperCase { 
    [self setString:[self uppercaseString]]; 
} 
@end 



    NSMutableArray *arrayTest = [[NSMutableArray alloc] init]; 
    [arrayTest addObject:[@"toto" mutableCopy]]; 
    [arrayTest addObject:[@"tata" mutableCopy]]; 
    [arrayTest addObject:[@"titi" mutableCopy]]; 
    [arrayTest addObject:[@"tutu" mutableCopy]]; 


    NSLog(@"%@", arrayTest); 

    [arrayTest makeObjectsPerformSelector:@selector(makeUpperCase)]; 

    NSLog(@"%@", arrayTest); 

但你可能不應該這樣做的。這味道非常糟糕。

這是好多了:

NSMutableArray *upperCaseArray = [NSMutableArray arrayWithCapacity:[arrayTest count]]; 
for (NSString *string in arrayTest) { 
    [upperCaseArray addObject:[string uppercaseString]]; 
} 
+0

謝謝你的例子。 –

相關問題