簡體   English   中英

在Objective-C中將對象添加到NSMutableArray

[英]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 ?我將不編輯主要問題,因為評論中的討論以及不將PointCGPoint的答案也很有趣。)

正如其他人指出的那樣,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。

https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSValue_Class/

例如,使用+ 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM