开发者

Objective C - 2 simple questions

  1. What is the difference between using @class & #import? I had开发者_如何学编程 a situation where i was getting a build error, and the solution was to use @class instead of #import to import my class.

  2. What does nonatomic mean? When do i use nonatomic to define a property, and when do i avoid it?


@class allows you to create a stub for a class that you will later define. For example:

MyOtherClass.h

@class MyClass;

@interface MyOtherClass : NSObject {
    MyClass *myObject;
}

MyOtherClass.m

#include "MyOtherClass.h"

@interface MyClass : NSObject {
    NSUInteger myInt;
}

#define is used to define strings that will be replaced by the preprocessor. For example:

#define MY_INT 5

x = MY_INT;

will be rewritten by the pre-processor as:

x = 5;


Scott G has already answered your question literally, but if, as Adam Ko said, you have meant #import, the answer would be that @class does not import the class but just tells the compiler that sometime later a class with the given name will be provided (in what is called "deferred binding" as I remember).

The @class is used mainly when you have two classes referring to each other, so they can not both import each other (that is probably the source of your compiler errors).

However, @class has a clear restriction that the compiler does not allow you to refer to any methods or attributes of the defined class. But usually you only need to use them in an implementation .m file, and there you can import the class without any problems.


An atomic property is one for which the getter is guaranteed to return a valid, meaningful value even if the relevant setter is being called simultaneously on another thread. That costs more in processing terms than a nonatomic property, but is safer for multithreaded code.


If you use atomic (which is default) it does some magic to make your code perfectly thread-safe.

This magic costs something and that's why you see keyword nonatomic often, people use it if they don't really care about thread safety to make their code faster.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜