jeudi 5 mars 2015

replace the NSMutableArray from mutableArrayValueForKey do extra set


Vote count:

0




I'm learning objective-c recently. The behavior of replacement of the NSMutableArray from mutableArrayValueForKey confused me. The code is as follows.



#import <Foundation/Foundation.h>

@interface ItemType : NSObject
@property(nonatomic) NSString* tag;
@end

@implementation ItemType
- (instancetype) initWithTagName:(NSString*) tag{
self = [super init];
if (self != nil) {
_tag = tag;
}
return self;

}

- (void) setTag:(NSString *)tag{
NSLog(@"setTag to:%@ with: %@", tag,_tag);
_tag = tag;
}

@end

int main(int argc, const char * argv[]) {
@autoreleasepool {
ItemType *item0 = [[ItemType alloc] initWithTagName:@"Alpha"];
ItemType *item1 = [[ItemType alloc] initWithTagName:@"Beta"];
ItemType *item2 = [[ItemType alloc] initWithTagName:@"Gamma"];
NSArray *items = @[item0, item1, item2];
NSMutableArray* tags = [items mutableArrayValueForKey:@"tag"];
NSLog(@"tags:%@",tags);
[tags replaceObjectAtIndex:1 withObject:@"Rho"];
NSLog(@"tags:%@",tags);
}
return 0;
}


and the result:



tags:(
Alpha,
Beta,
Gamma
)
setTag to:(
Alpha,
Rho,
Gamma
) with: Alpha
setTag to:(
Alpha,
Rho,
Gamma
) with: Beta
setTag to:(
Alpha,
Rho,
Gamma
) with: Gamma
tags:(
(
Alpha,
Rho,
Gamma
),
(
Alpha,
Rho,
Gamma
),
(
Alpha,
Rho,
Gamma
)
)


I wonder why the extra setTag are called. Thank you very much.



asked 1 min ago







replace the NSMutableArray from mutableArrayValueForKey do extra set

Aucun commentaire:

Enregistrer un commentaire