我們知道,數(shù)組中添加一個對象,會使對象的引用計數(shù)加1,被數(shù)組所持有。
如下是我們常用的使用,并打印對象引用計數(shù)。如果有需求在數(shù)組保持對象的弱引用,對象移除時,數(shù)組中也隨之移除,那要怎么處理。
本文介紹NSPointerArray、NSHashTable、NSMapTable實現(xiàn)對象的弱引用。
這里寫圖片描述
1、iOS6.0之前,可以用[NSValue valueWithNonretainedObject:person]獲取到對象的value,將這個value添加到數(shù)組中。效果如下:
這里寫圖片描述
對于[NSValue valueWithNonretainedObject:NSObject];
這里寫圖片描述
官方介紹:這個方法是有用的,如果你想添加一個對象集合,但不想集合創(chuàng)建一個強引用。
2、在iOS6.0之后出現(xiàn)了NSPointerArray。
他的初始化方法,可以創(chuàng)建強引用,弱引用對象的數(shù)組
+ (NSPointerArray *)strongObjectsPointerArray NS_AVAILABLE(10_8, 6_0);
+ (NSPointerArray *)weakObjectsPointerArray NS_AVAILABLE(10_8, 6_0);
這里寫圖片描述
當(dāng)對象被釋放后,數(shù)組中同時會置為NULL;我們可以通過該API來操作數(shù)組。
- (void)compact; // eliminate NULLs
// Getter: the number of elements in the array, including NULLs
// Setter: sets desired number of elements, adding NULLs or removing items as necessary.
@property NSUInteger count;
@end
@interface NSPointerArray (NSPointerArrayConveniences)
// construction
#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE))
+ (id) pointerArrayWithStrongObjects NS_DEPRECATED_MAC(10_5, 10_8); // strong objects
+ (id) pointerArrayWithWeakObjects NS_DEPRECATED_MAC(10_5, 10_8); // weak objects
#endif
+ (NSPointerArray *)strongObjectsPointerArray NS_AVAILABLE(10_8, 6_0);
+ (NSPointerArray *)weakObjectsPointerArray NS_AVAILABLE(10_8, 6_0);
@property (readonly, copy) NSArray *allObjects;
3、同樣,在iOS6.0之后,有NSHashTable類似于NSSet ,有NSMapTable為NSDictionary ,具體使用方法可以參考API。
參考文章:
https://blog.csdn.net/shaohua_lv/article/details/70257053