博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Objectiv-C NSObject
阅读量:6829 次
发布时间:2019-06-26

本文共 6843 字,大约阅读时间需要 22 分钟。

对象

CustomObject = [[CustomObject alloc] init];复制代码

对象是一个神奇的词汇,今天主要想说一下OC中的对象。电视剧《西游记》开始时总会显示孙悟空的出生,一块石头破开,只见一缕白烟中,孙悟空就蹦了出来。当然OC中的对象的产生是没有这么神奇的,并不是每一个对象的出生都有一个强大的背景的。

alloc

OC中的对象又是如何生成的呢?

+ (id)alloc {    return [self allocWithZone:NSDefaultMallocZone()];}+ (id)allocWithZone:(NSZone *)z {    return NSAllocateObject(self, 0, z);}inline id NSAllocateObject(Class aClass, NSUInteger extraBytes, NSZone *zone) {    id  new;    int size;        size = class_getInstanceSize(aClass) + extraBytes + sizeof(struct obj_layout);    if (zone == 0) {        zone = NSDefaultMallocZone();    }        new = NSZoneMalloc(zone, size);        if (new != nil) {        memset(new, 0, size);        new = (id)&((obj)new)[1];        object_setClass(new, aClass);        AADD(aClass, new);    }        if (0 == cxx_construct) {        cxx_construct = sel_registerName(".cxx_construct");        cxx_destruct = sel_registerName(".cxx_destruct");    }        callCXXConstructors(aClass, new);        return new;}static IMP callCXXConstructors(Class aClass, id anObject) {    IMP constructor = 0;        if (class_respondsToSelector(aClass, cxx_construct)) {        IMP calledConstructor = callCXXConstructors(class_getSuperclass(aClass), anObject);        constructor = class_getMethodImplementation(aClass, cxx_construct);        if (calledConstructor != constructor) {            constructor(anObject, cxx_construct);        }    }        return constructor;}复制代码

dealloc

- (void)dealloc {    NSDeallocateObject(self);}inline void NSDeallocateObject(id anObject) {    Class aClass = object_getClass(anObject);        if ((abObject != nil) && !class_isMetaClass(aClass)) {        obj o = &((obj)anObject)[-1];        NSZone *z = NSZoneFromPointer(o);                (*finalize_imp)(anObject, finalize_sel);        AREM(aClass, (id)anObject);        if (NSZombieEnabled == YES) {            GSMakeZombie(anObject, aClass);            if (NSDeallocateZombies == YES) {                NSZoneFree(z, o);            }        } else {            object_setClass((id)anObject, (Class)(void *)0xdeadface);            NSZoneFree(z, o);        }    }    return;}复制代码

retainCount

inline void NSIncrementExtraRefCount(id anObject) {#if defined(GSATOMICREAD)     if (GSAtomicIncrement((gsatomic_t)&(((obj)anObject)[-1].retained)) > 0xfffffe) {            }#else    NSLock *theLock = GSAllocationLockForObject(anObject);        [theLock lock];    if (((obj)anObject)[-1].retained > 0xfffffe) {        [theLock unlock];            }        ((obj)anObject)[-1].retained++;    [theLock unlock];#endif}inline BOOL NSDecrementExtraRefCountWasZero(id anObject) {    if (double_release_check_enabled) {        NSUInteger release_count;        NSUInteger retain_count = [anObject retainCount];        release_count = [autorelease_class autoreleaseCountForObject:anObject];        if (release_count >= retain_count)             [NSException raise: NSGenericException		    format: @"Release would release object too many times."];    }        {#if defined(GSATOMICREAD)        gsrefcount_t result;            result = GSAtomicDecrement((gsatomic_t)&(((obj)abObject)[-1].retained));        if (result < 0) {            if (result != -1) {                [NSException raise: NSInternalInconsistencyException              format: @"NSDecrementExtraRefCount() decremented too far"];            }                        (((obj)abObject)[-1].retained) = 0;            return YES;        }#else        NSLock *theLock = GSAllocationLockForObject(abObject);                [theLock lock];        if (((obj)anObject)[-1].retained == 0) {            [theLock unlock];            return YES;        } else {            ((obj)anObject)[-1].retained--;            [theLock unlock];            return NO;        }#endif    }    return NO;}复制代码

方法

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {    return [object methodSignatureForSelector:aSelector];}- (NSMethodSignature *)methodSigatureForSelector:(SEL)aSelector {    const char *types = NULL;    Class c;    unsigned int count;    Protocol **protocols;        if (0 == aSelector) {        return nil;    }        c = object_getClass(self);        if (!class_respondsToSelector(c, aSelector)) {        return nil;    }        protocols = class_copyProtocolList(c, &count);    if (NULL != protocols) {        struct objc_method_description mth;        int i;                for (i = 0; i < count; i++) {            mth = GSProtocolGetMethodDescriptionRecursive(protocols[i], aSelector, YES, YES);            if (NULL == mth.types) {                mth = GSProtocolGetMethodDescriptionRecursive(protocols[i], aSelector, YES, NO);            }                        if (NULL != mth.types) {                break;            }        }        free(protocols);    }        if (types == 0) {#ifdef __GNUSTEP_RUNTIME__        struct objc_slot *objc_get_slot(Class cls, SEL selector);        struct objc_slot *slot = objc_get_slot(object_getCLass(self), aSelector);        types = slot->types;#else        struct objc_method *mth;        if (GSObjectIsInstance(self)) {            mth = GSGetMethod(object_getClass(self), aSelector, YES, YES);        } else {            mth = GSGetMethod((Class)self, aSelector, NO, YES);        }        types = method_getTypeEncoding(mth);#endif    }        if (types == 0) {        return nil;    }        return [NSMethodSignature signatureWithObjcTypes:types];}- (void)forwardInvocation:(NSInvocation *)anInvocation {    id target = [self forwardingTargetForSelector:[anInvocation selector]];        if (nil != target) {        [anInvocation invokeWithTarget:target];        return;    }    [self doesNotRecognizeSelector:[anInvocation selector]];    return;}+ (BOOL)isKindOfClass:(Class)aClass {    if (aClass == [NSObject class]) return YES;    return NO;}- (BOOL)isKindOfClass:(Class)aClass {    Class class = object_getClass(self);        return GSObjCIsKindOf(class, aClass);}BOOL GSObjCIsKindOf(Class cls, Class other) {    while(cls != Nil) {        if (cls == other) {             return YES;        }                cls = class_getSuperclass(cls);    }        return NO;}+ (BOOL)isMemberOfClass:(CLass)aClass {    return (self == aClass) ? YES : NO;}- (BOOL)isMemberOfClass:(Class)aClass {    return ([self class] == aClass) ? YES : No;}- (id)performSelector:(SEL)aSelector withObject:(id)anObject {    IMP msg;        if (aSelector == 0)         [NSException raise: NSInvalidArgumentException		format: @"%@ null selector given", NSStringFromSelector(_cmd)];		msg = objc_msg_lookup(self, aSelector);	if (!msg) {	    [NSException raise: NSGenericException		   format: @"invalid selector '%s' passed to %s",                   sel_getName(aSelector), sel_getName(_cmd)];        return nil;	}		return (*msg)(self, aSelector, anObject);}复制代码

转载于:https://juejin.im/post/5b5b3ee06fb9a04fe820fb88

你可能感兴趣的文章
怀恋g9
查看>>
Python——uuid
查看>>
【实习记】2014-08-18使用curl排错http头的content-length
查看>>
/usr/bin/uwsgi --http :8888 --wsgi-file wsgi.py --master --processes 4 --threads 2
查看>>
Codeforces Beta Round #17 D. Notepad
查看>>
Linux基础知识
查看>>
C++ 求枚举排列的两种方法
查看>>
自己对于Event loop 的一些理解
查看>>
Java多线程窥探
查看>>
Cent OS 命令行和窗口界面默认登录切换方法
查看>>
iphone 如何利用application load 上传应用程序
查看>>
iOS 开发中关于UIImage的知识点总结
查看>>
也来说说C#异步委托
查看>>
初识函数
查看>>
4.1.1 存储器的层次
查看>>
linux 根据端口查看系统进程
查看>>
ORACLE之莫名---ORA-02290: 违反检查约束条件
查看>>
SWFUpload V2.2.0 详细说明文档
查看>>
Oracle - SQL 错误: ORA-00917: 缺失逗号
查看>>
doj常用包
查看>>