Programing

@property는 Objective-C에서 비 원자 유지, 할당, 복사,

lottogame 2020. 5. 1. 07:58
반응형

@property는 Objective-C에서 비 원자 유지, 할당, 복사,


Objective-C를 처음 접하는 사람이 누군가 @property 지시문을 따르는 유지, 할당, 복사 및 누락 된 다른 항목에 대한 개요를 알려줄 수 있습니까? 그들은 무엇을하고 있으며 왜 서로를 사용하고 싶습니까?


MrMage가 링크 한 기사가 더 이상 작동하지 않습니다. 그래서 Objective-C에서 (매우) 짧은 시간 코딩으로 배운 내용은 다음과 같습니다.

비 원자 대 원자- "원자"가 기본값입니다. 항상 "비 원자"를 사용하십시오. 나는 왜 그런지 모르겠지만, 읽은 책에는 "원자"를 사용하는 "드물게 이유"가 있다고 말했다. (BTW : 내가 읽은 책은 BNR "iOS Programming"책입니다.)

readwrite vs. readonly- "readwrite"가 기본값입니다. @synthesize하면 getter와 setter가 모두 생성됩니다. "readonly"를 사용하면 setter가 생성되지 않습니다. 객체의 인스턴스화 후에 절대 변경하고 싶지 않은 값으로 사용하십시오.

유지 대 복사 대 할당

  • "할당"이 기본값입니다. @synthesize에 의해 생성 된 setter에서 값은 단순히 속성에 할당됩니다. 나는 포인터가 아닌 속성에 "할당"을 사용해야한다는 것을 이해하고 있습니다.
  • 속성이 객체에 대한 포인터 인 경우 "보존"이 필요합니다. @synthesize에 의해 생성 된 setter는 객체를 유지합니다 (일명 유지 횟수 추가). 작업이 끝나면 개체를 해제해야합니다.
  • 개체가 변경 가능한 경우 "복사"가 필요합니다. 이 시점에서 객체의 값이 필요하고 해당 값이 객체의 다른 소유자가 변경 한 내용을 반영하지 않도록하려면이 옵션을 사용하십시오. 사본을 보유하고 있으므로 오브젝트를 완료하면 오브젝트를 해제해야합니다.

@property의 속성에 대해 알기 전에 @property의 사용법이 무엇인지 알아야합니다.

  • @property 는 클래스가 캡슐화 할 정보를 정의하는 방법을 제공합니다. @property를 사용하여 객체 / 변수를 선언 하면 해당 객체 / 변수는 해당 클래스를 가져 오는 다른 클래스에서 액세스 할 수 있습니다.

  • 헤더 파일에서 @property사용하여 객체를 선언 하면 구현 파일에서 @synthesize사용하여 객체 를 합성해야 합니다. 이것은 객체 KVC를 준수 합니다. 기본적으로 컴파일러는 이 객체에 대한 접근 자 메서드합성 합니다.

  • 접근 자 메소드는 setter 및 getter입니다.

예 : .h

@interface XYZClass : NSObject
@property (nonatomic, retain) NSString *name;
@end

.미디엄

@implementation XYZClass
@synthesize name;
@end

이제 컴파일러는 name에 대한 접근 자 메서드를 합성 합니다.

XYZClass *obj=[[XYZClass alloc]init];
NSString *name1=[obj name]; // get 'name'
[obj setName:@"liza"]; // first letter of 'name' becomes capital in setter method
  • @property 의 속성 목록

    원자, 비 원자, 유지, 복사, 읽기 전용, 읽기 / 쓰기, 할당, 강함, getter = method, setter = method, unsafe_unretained

  • 원자가 기본 동작입니다. 객체가 원자로 선언되면 스레드로부터 안전 해집니다. 스레드 안전은 한 번에 해당 클래스의 특정 인스턴스에서 하나의 스레드 만 해당 개체를 제어 할 수 있음을 의미합니다.

스레드가 getter 메소드를 수행중인 경우 다른 스레드가 해당 오브젝트에서 setter 메소드를 수행 할 수 없습니다. 느립니다.

@property NSString *name; //by default atomic`
@property (atomic)NSString *name; // explicitly declared atomic`
  • 비원 자는 스레드 안전하지 않습니다. nonatomic 속성 특성을 사용하여 합성 된 접근자가 단순히 값을 직접 설정하거나 반환하도록 지정하면 동일한 값이 다른 스레드에서 동시에 액세스 될 경우 어떤 일이 발생하는지 보장 할 수 없습니다.

이러한 이유로 원자 이외의 특성에 액세스하는 것이 더 빠릅니다.

@property (nonatomic)NSString *name;   
  • 속성이 객체에 대한 포인터 인 경우 유지 가 필요합니다.

setter 메소드는 오브젝트의 보유 수를 증가시켜 자동 릴리스 풀의 메모리를 차지합니다.

@property (retain)NSString *name;
  • copy copy 를 사용하면 retain을 사용할 수 없습니다. 클래스의 사본 인스턴스를 사용하면 자체 사본이 포함됩니다.

변경 가능한 문자열이 설정되고 이후에 변경 되더라도 인스턴스는 설정 당시의 값을 캡처합니다. setter 및 getter 메소드는 합성되지 않습니다.

@property (copy) NSString *name;

지금,

NSMutableString *nameString = [NSMutableString stringWithString:@"Liza"];    
xyzObj.name = nameString;    
[nameString appendString:@"Pizza"]; 

이름 은 영향을받지 않습니다.

  • readonly setter 메서드를 통해 속성을 변경하지 않으려면 속성을 읽기 전용으로 선언 할 수 있습니다.

컴파일러는 getter를 생성하지만 setter는 생성하지 않습니다.

@property (readonly) NSString *name;
  • readwrite 가 기본 동작입니다. readwrite 속성을 명시 적으로 지정할 필요는 없습니다.

읽기 전용과 반대입니다.

@property (readwrite) NSString *name;
  • assign will generate a setter which assigns the value to the instance variable directly, rather than copying or retaining it. This is best for primitive types like NSInteger and CGFloat, or objects you don't directly own, such as delegates.

Keep in mind retain and assign are basically interchangeable when garbage collection is enabled.

@property (assign) NSInteger year;
  • strong is a replacement for retain.

It comes with ARC.

@property (nonatomic, strong) AVPlayer *player; 
  • getter=method If you want to use a different name for a getter method, it’s possible to specify a custom name by adding attributes to the property.

In the case of Boolean properties (properties that have a YES or NO value), it’s customary for the getter method to start with the word “is”

@property (getter=isFinished) BOOL finished;
  • setter=method If you want to use a different name for a setter method, it’s possible to specify a custom name by adding attributes to the property.

The method should end with a colon.

@property(setter = boolBool:) BOOL finished;
  • unsafe_unretained There are a few classes in Cocoa and Cocoa Touch that don’t yet support weak references, which means you can’t declare a weak property or weak local variable to keep track of them. These classes include NSTextView, NSFont and NSColorSpace,etc. If you need to use a weak reference to one of these classes, you must use an unsafe reference.

An unsafe reference is similar to a weak reference in that it doesn’t keep its related object alive, but it won’t be set to nil if the destination object is deallocated.

@property (unsafe_unretained) NSObject *unsafeProperty;

If you need to specify multiple attributes, simply include them as a comma-separated list, like this:

@property (readonly, getter=isFinished) BOOL finished;

After reading many articles I decided to put all the attributes information together:

  1. atomic //default
  2. nonatomic
  3. strong=retain //default
  4. weak= unsafe_unretained
  5. retain
  6. assign //default
  7. unsafe_unretained
  8. copy
  9. readonly
  10. readwrite //default

Below is a link to the detailed article where you can find these attributes.

Many thanks to all the people who give best answers here!!

Variable property attributes or Modifiers in iOS

Here is the Sample Description from Article

  1. atomic -Atomic means only one thread access the variable(static type). -Atomic is thread safe. -but it is slow in performance -atomic is default behavior -Atomic accessors in a non garbage collected environment (i.e. when using retain/release/autorelease) will use a lock to ensure that another thread doesn't interfere with the correct setting/getting of the value. -it is not actually a keyword.

Example :

@property (retain) NSString *name;

@synthesize name;
  1. nonatomic -Nonatomic means multiple thread access the variable(dynamic type). -Nonatomic is thread unsafe. -but it is fast in performance -Nonatomic is NOT default behavior,we need to add nonatomic keyword in property attribute. -it may result in unexpected behavior, when two different process (threads) access the same variable at the same time.

Example:

@property (nonatomic, retain) NSString *name;

@synthesize name;

Explain:

Suppose there is an atomic string property called "name", and if you call [self setName:@"A"] from thread A, call [self setName:@"B"] from thread B, and call [self name] from thread C, then all operation on different thread will be performed serially which means if one thread is executing setter or getter, then other threads will wait. This makes property "name" read/write safe but if another thread D calls [name release] simultaneously then this operation might produce a crash because there is no setter/getter call involved here. Which means an object is read/write safe (ATOMIC) but not thread safe as another threads can simultaneously send any type of messages to the object. Developer should ensure thread safety for such objects.

If the property "name" was nonatomic, then all threads in above example - A,B, C and D will execute simultaneously producing any unpredictable result. In case of atomic, Either one of A, B or C will execute first but D can still execute in parallel.

  1. strong (iOS4 = retain ) -it says "keep this in the heap until I don't point to it anymore" -in other words " I'am the owner, you cannot dealloc this before aim fine with that same as retain" -You use strong only if you need to retain the object. -By default all instance variables and local variables are strong pointers. -We generally use strong for UIViewControllers (UI item's parents) -strong is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong means that you own the object.

Example:

@property (strong, nonatomic) ViewController *viewController;

@synthesize viewController;
  1. weak (iOS4 = unsafe_unretained ) -it says "keep this as long as someone else points to it strongly" -the same thing as assign, no retain or release -A "weak" reference is a reference that you do not retain. -We generally use weak for IBOutlets (UIViewController's Childs).This works because the child object only needs to exist as long as the parent object does. -a weak reference is a reference that does not protect the referenced object from collection by a garbage collector. -Weak is essentially assign, a unretained property. Except the when the object is deallocated the weak pointer is automatically set to nil

Example :

@property (weak, nonatomic) IBOutlet UIButton *myButton;

@synthesize myButton;

Strong & Weak Explanation, Thanks to BJ Homer:

Imagine our object is a dog, and that the dog wants to run away (be deallocated). Strong pointers are like a leash on the dog. As long as you have the leash attached to the dog, the dog will not run away. If five people attach their leash to one dog, (five strong pointers to one object), then the dog will not run away until all five leashes are detached. Weak pointers, on the other hand, are like little kids pointing at the dog and saying "Look! A dog!" As long as the dog is still on the leash, the little kids can still see the dog, and they'll still point to it. As soon as all the leashes are detached, though, the dog runs away no matter how many little kids are pointing to it. As soon as the last strong pointer (leash) no longer points to an object, the object will be deallocated, and all weak pointers will be zeroed out. When we use weak? The only time you would want to use weak, is if you wanted to avoid retain cycles (e.g. the parent retains the child and the child retains the parent so neither is ever released).

  1. retain = strong -it is retained, old value is released and it is assigned -retain specifies the new value should be sent -retain on assignment and the old value sent -release -retain is the same as strong. -apple says if you write retain it will auto converted/work like strong only. -methods like "alloc" include an implicit "retain"

Example:

@property (nonatomic, retain) NSString *name;

@synthesize name;
  1. assign -assign is the default and simply performs a variable assignment -assign is a property attribute that tells the compiler how to synthesize the property's setter implementation -I would use assign for C primitive properties and weak for weak references to Objective-C objects.

Example:

@property (nonatomic, assign) NSString *address;

@synthesize address;
  1. unsafe_unretained

    -unsafe_unretained is an ownership qualifier that tells ARC how to insert retain/release calls -unsafe_unretained is the ARC version of assign.

Example:

@property (nonatomic, unsafe_unretained) NSString *nickName;

@synthesize nickName;
  1. copy -copy is required when the object is mutable. -copy specifies the new value should be sent -copy on assignment and the old value sent -release. -copy is like retain returns an object which you must explicitly release (e.g., in dealloc) in non-garbage collected environments. -if you use copy then you still need to release that in dealloc. -Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.

Example:

@property (nonatomic, copy) NSArray *myArray;

@synthesize myArray;

Atomic property can be accessed by only one thread at a time. It is thread safe. Default is atomic .Please note that there is no keyword atomic

Nonatomic means multiple thread can access the item .It is thread unsafe

So one should be very careful while using atomic .As it affect the performance of your code

참고URL : https://stackoverflow.com/questions/2255861/property-retain-assign-copy-nonatomic-in-objective-c

반응형