Date
Dec. 4th, 2024
 
2024年 11月 4日

Post: Obj-C: Associate struct value to your object

Obj-C: Associate struct value to your object

Published 12:04 Apr 21, 2015.

Created by @ezra. Categorized in #Programming, and tagged as #iOS.

Source format: Markdown

Table of Content

The value of function OBJC_EXPORT void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy) must be an Objective-C object. We need to wrap the struct in an Objective-C class.

StructType s = ...;
NSValue* value = [NSValue valueWithBytes:&s objCType:@encode(StructType)];
objc_setAssociatedObject(obj, SPECIAL_KEY, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
// ...
NSValue* value = objc_getAssociatedObject(obj, SPECIAL_KEY);
StructType s;
[value getValue:&s];
Pinned Message
HOTODOGO
The Founder and CEO of Infeca Technology.
Developer, Designer, Blogger.
Big fan of Apple, Love of colour.
Feel free to contact me.
反曲点科技创始人和首席执行官。
开发、设计与写作皆为所长。
热爱苹果、钟情色彩。
随时恭候 垂询