【问题标题】:iOS NSMutableArray initial custom objectiOS NSMutableArray 初始自定义对象
【发布时间】:2015-12-06 14:59:39
【问题描述】:

如何初始化自定义对象?

我有很多点数据,所以我创建了点数据对象(类),如下所示:

MyPoint.h

 #import <Foundation/Foundation.h>

 @interface MyPoint : NSObject

 @property (assign, nonatomic) NSString*  pointName;
 @property (assign, nonatomic) NSString*  lat;
 @property (assign, nonatomic) NSString*  lng;

 @end

然后数据会合成很多区域,所以我在 MyArea.h 中创建其他对象

 #import "MyPoint.h"

 @interface MyArea : NSObject


@property (assign, nonatomic) NSString*  areaName;

 @property(strong,nonatomic) NSMutableArray<MyPoint*> *myPoint; // --1

 @end

如何在 myArea.m 中初始化 myPoint?

我不确定下面哪个声明是正确的:

 @property(strong,nonatomic) NSMutableArray<MyPoint*> *myPoint;

 @property(strong,nonatomic) NSMutableArray<MyPoint> *myPoint;

以及如何在 .m 文件中使用我的自定义对象(MyPoint)创建 NSMutableArray。

在 MyArea.m 中

 #import "MyArea.h"

 @implementation MyArea

 -(id) init{
     self = [super init];
     if (self) {
         self.myPoint = [NSMutableArray<MyPoint*> new ];  // ??
   }
     return self;
 }
 @end

有没有人可以教我如何在objective-c中创建模型。

我将获取大量数据,然后将其设置到 MyArea 对象中。

非常感谢。

【问题讨论】:

  • 究竟是什么不工作?看不到问题
  • myPoint 属性声明的第二个选项是正确的。请记住,它是一个 NSMutableArray 指针,其中包含指向 MyPoint 对象的指针。

标签: ios objective-c model nsmutablearray


【解决方案1】:

你需要编写一个自定义的 initWithPoints:(NSMutableArray)points。

例如:

- (instanceType)initWithPoints:(NSMutableArray<MyPoint *> *)points
{
    self = [super init];
    if(self) {
        NSLog(@"_init: %@", self);
        self.myPoint = points
    }
    return self;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    • 1970-01-01
    相关资源
    最近更新 更多