如何将CGRect值存储在NSMutableArray中?

114

我如何将CGRect对象存储在NSMutableArray中,然后稍后再检索它们?

4个回答

294

你需要将CG结构体包装在NSValue类中。因此:

NSMutableArray* array = [NSMutableArray mutableArray];
[array addObject:[NSValue valueWithCGRect:CGRectMake(0,0,10,10)]];
CGRect someRect = [[array objectAtIndex:0] CGRectValue];

更多示例请参见:http://iosdevelopertips.com/cocoa/storing-cgpoint-cgsize-and-cgrect-in-collections-using-nsvalue.html - WINSergey
很棒的答案!如果您演示将存储的NSValue“拆箱”回CGRect,那就更有用了。 - Motti Shneor
1
不支持MacOS操作系统。 - Cliff Ribaudo

12
CGRect rect = CGRectMake( 5, 5, 40, 30 );
NSString* rectAsString = NSStringFromCGRect( rect );
CGRect original = CGRectFromString( rectAsString );

虽然这种方法确实有效,但我们能否避免推广这样的不良做法呢?至少要在这种方法上加上一些关于潜在问题的警告。 - undefined

2
我们将CGRectCGPointCMTime对象存储在一个NSMutableArray中。您可以使用以下代码将它们添加到数组中:
[arrayName addObject:[NSValue valueWithCGPoint:MyCGPoint]]
[arrayName addObject:[NSValue valueWithCGRect:MyCGRect]]
[arrayName addObject:[NSValue valueWithCMTime:MyCMTime]]
[arrayName addObject:[NSValue valueWithCMTimeRange:MyCMTimeRange]]

1
Store string in array.and then get back string and convert that in CGRect back as per the need.
CGRect rect = CGRectMake( 5, 5, 40, 30 );
NSString* rectAsString = NSStringFromCGRect( rect );
NSMutableArray* array = [NSMutableArray mutableArray];
[array addObject:rectAsString];

For converting string in CGRect back use:-
CGRect rect9 = CGRectFromString(rectAsString);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接