Sys*_*ank 0 cocoa pointers objective-c
我有一个类必须以相同的方式初始化一组类似的对象.
NSNumber *a = nil;
NSNumber *b = nil;
NSNumber *c = nil;
Run Code Online (Sandbox Code Playgroud)
a,b和c是现有对象的成员变量.在我的代码中,我使用了一个更复杂的NSObject子类,但是这个例子使用NSNumbers更容易理解.
必须以类似的方式初始化所有3个对象.因此,我想构建一个指针数组,我可以在for循环中使用,如下所示:
NSPointerArray *objs = [NSPointerArray weakObjectsPointerArray];
[objs addPointer:&a];
[objs addPointer:&b];
[objs addPointer:&c];
Run Code Online (Sandbox Code Playgroud)
运行上面的代码我收到以下错误:
error: address doesn't contain a section that points to a section in a object file
Run Code Online (Sandbox Code Playgroud)
我怎样才能构建一个我可以用这样的循环探索的数组?
for (id *o in objs) {
*o = @2;
}
Run Code Online (Sandbox Code Playgroud)
只需将指针包装在'NSValue'对象中,就可以了
id v1 = [NSValue valueWithPointer:p1];
id v2 = [NSValue valueWithPointer:p2];
id v3 = [NSValue valueWithPointer:p3];
id array = @[v1,v2,v3];
for(NSValue *value in array) {
void *pointer = value.pointerValue;
NSNumber *n = (__bridge NSNumber*)pointer;
}
Run Code Online (Sandbox Code Playgroud)
出现你想做的演示:(NSNumbers是不可变的)
#import <Foundation/Foundation.h>
int main(int argc, char *argv[]) {
@autoreleasepool {
NSNumber *a;
NSNumber *b;
NSArray *os = @[ [NSValue valueWithPointer:&a],
[NSValue valueWithPointer:&b] ];
for (NSValue *v in os) {
void *pointer = [v pointerValue];
NSNumber **n_ptr = (__bridge NSNumber**)pointer;
*n_ptr = @2.0;
}
NSLog(@"%@ %@", a,b);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1737 次 |
| 最近记录: |