根据实例获取实例名

首先import<objc/runtime.h>


- (NSString *)nameWithInstance:(id)instance
{
    unsigned int numIvars = 0; 
    NSString *key=nil;
    Ivar * ivars = class_copyIvarList([self class], &numIvars); 
    for(int i = 0; i < numIvars; i++) { 
        Ivar thisIvar = ivars[i];
        const char *type = ivar_getTypeEncoding(thisIvar); 
        NSString *stringType =  [NSString stringWithCString:type encoding:NSUTF8StringEncoding];
        if (![stringType hasPrefix:@"@"]) { 
            continue;
        }
        if ((object_getIvar(self, thisIvar) == instance)) { 
           key = [NSString stringWithUTF8String:ivar_getName(thisIvar)];
            break;
        }
    }
    free(ivars);
    return key; 
}

 

 

posted @ 2013-10-28 16:49  爱笑的雷小豆  阅读(496)  评论(0编辑  收藏  举报