馬上就要回家過年了,身為偉大的程式員,過年怎麼能不帶個妹子回家呢,沒有妹子的怎麼辦?
沒關係,我們new一個貝
NSMutableDictionary *me = [NSMutableDictionary dictionary]; // 從 GirlEntity類 建立一個妹子 GirlEntity *girl1 = [[[GirlEntity alloc] init] autorelease]; girl1.name = @"妹子1"; [me setObject:girl1 forKey:@"girlFriend"];
diaosi說從來沒有過妹子,不知道妹子類是什麼.
沒關係,我們自己造
// 建立一個NSObject對象, 然後添加屬性,把他設定成妹子 NSObject *girl2 = [[[NSObject alloc] init] autorelease]; objc_setAssociatedObject(girl2, "name", @"妹子2", OBJC_ASSOCIATION_COPY); [me setObject:girl2 forKey:@"girlFriend2"];
屌絲說這樣還不夠徹底.
沒關係,我們自己new一個類出來
// 動態建立一個妹子類,然後建立一個妹子 const char *className = "Girl3"; Class kclass = objc_getClass(className); if (!kclass) { Class superClass = [NSObject class]; kclass = objc_allocateClassPair(superClass, className, 0); } NSUInteger size; NSUInteger alignment; NSGetSizeAndAlignment("*", &size, &alignment); class_addIvar(kclass, "name", size, alignment, "*"); // 註冊到運行時環境 objc_registerClassPair(kclass); id girl3 = [[[kclass alloc] init] autorelease]; object_setInstanceVariable(girl3, "name", "妹子3"); [me setObject:girl3 forKey:@"girlFriend3"];
如果想帶女神回去怎辦?
沒關係,我們可以挖牆角
// 挖牆角 GirlEntity *girl4 = [[[GirlEntity alloc] init] autorelease]; girl4.name = @"女神"; SEL original = @selector(talk); SEL replacement = @selector(talk2); Method a = class_getInstanceMethod([GirlEntity class], original); Method b = class_getInstanceMethod([self class], replacement); if (class_addMethod([GirlEntity class], original, method_getImplementation(b), method_getTypeEncoding(b))) { class_replaceMethod([GirlEntity class], replacement, method_getImplementation(a), method_getTypeEncoding(a)); } else { method_exchangeImplementations(a, b); } [girl4 talk];-(void) talk2{ NSString *name = [self valueForKey:@"name"]; if ([name isEqualToString:@"女神"]) { // do 你懂的 NSLog(@"%s", __FUNCTION__); }}