[英]Objective-C NSMutableArray: Problem with sorting objects?
[英]Adding objects to an NSMutableArray in Objective-C
我遇到了必须是相当简单的任务:将对象添加到Objective-C中的NSMutableArray
。 这是我已经尝试过的数百万种方法:
NSMutableArray* foregroundPoints;
Point point;
// Fails with "No viable conversion from 'Point' to 'id _Nonnull'"
[foregroundPoints addObject: point];
// Fails with "Cannot initialise a parameter of type 'id _Nonull' with an rvalue of type 'Point *'"
[foregroundPoints addObject: &point];
// Fails with: "Illegal type 'Point' used in boxed expression"
[foregroundPoints addObject: @(point)];
Point *pointPtr;
// Fails with "Cannot initialise a parameter of type 'id _Nonull' with an lvalue of type 'Point *'"
[foregroundPoints addObject: pointPtr];
// Fails with "Cannot initialise a parameter of type 'id _Nonull' with an rvalue of type 'Point **'"
[foregroundPoints addObject: &pointPtr];
//Fails with: "Illegal type 'Point *' used in boxed expression"
[foregroundPoints addObject: @(pointPtr)];
我应该怎么做才能将Point
添加到我的NSMutableArray
?
(注:从评论和一些答案中,我发现我对Point
感到困惑。我以为这是一个Objective-C库类,但实际上,这是从我项目的其他地方获得的C ++结构。)真正归结为:我如何将CGPoint
添加到NSMutableArray
?我将不编辑主要问题,因为评论中的讨论以及不将Point
和CGPoint
的答案也很有趣。)
正如其他人指出的那样,NSArray仅保存Objective-C对象。 要保存C类型,您需要将它们装在对象中。
您需要在此处使用NSValue或NSString。 NSValue具有针对最常见的Foundation结构和基元的装箱方法。
对于其中的一些,还有一些函数也可以与NSString进行相互转换。 请参阅《基础功能参考》。
标量C类型可以使用NSValue子类NSNumber进行装箱和拆箱
nil必须使用NSNull表示
问题在于只能将对象添加到诸如NSArray或NSDictionary之类的集合中。
将您的“点”(可能是CGPoint或NSPoint struct )转换为可以添加到数组中的NSValue对象。
使用此类可处理集合中的此类数据类型(例如NSArray和NSSet),键值编码以及其他需要Objective-C对象的API。
例如,使用+ valueWithCGPoint:
将点转换为可以添加到数组的NSValue表示形式。
CGPoint point;
NSValue *pointValue = [NSValue valueWithCGPoint:point];
[foregroundPoints addObject:pointValue];
然后,稍后使用- CGPointValue
将对象转换回原始类型。
@pkamb的答案是这样。
但是,如果需要性能,请使用标准C数组存储点,而不要多次调用valueWithCGPoint和CGPointValue。
将其嵌入NSObject(例如,命名为PointArray)中进行操作。
@interface PointArray : NSObject
-(Point)pointAtIndex:(NSUInteger)index;
-(void)addPoint:(Point)point;
…
@property(nonatomic,readonly) NSUInteger numberOfPoints;
@end
@implementation PointArray
{
Point *points;
NSUInteger numberOfPoints;
}
// You'll have to work a bit there ..
@end
您正在尝试使用NSArray初始化NSMutableArray对象。
你为什么不试试这个...
foregroundPoints = [NSMutableArray arrayWithObjects: @(startPoint), @(endPoint), nil];
不使用NSArray初始化NSMutableArray前景色点到NSMutableArray。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.