initWithObject之后NSMutableArray计数为0

时间:2017-09-11 18:47:21

标签: ios objective-c

我已经定义了NSMutableArray的属性。在致电initWithObjects后,它count为0.我在这里缺少什么?这是我的代码:

@interface MainViewController ()
@property NSMutableArray *photos;
@end

- (void)viewDidLoad {
    [super viewDidLoad];

    _photos = [_photos initWithObjects:@"1", @"2", @"3", nil];
    NSLog(@"Photos count: %lu",(unsigned long)_photos.count); //prints 0
}

2 个答案:

答案 0 :(得分:5)

这是因为您尝试调用_photos方法时nilinit。请改用arrayWithObjects

_photos = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", nil];

答案 1 :(得分:3)

非法init...中说alloc并且在同一行中说alloc_photos = [[NSMutableArray alloc] initWithObjects:@"1", @"2", @"3", nil]; 是一个类方法,你的类是NSMutableArray,所以你应该说:

public class control_it extends HttpServlet{
private static final long serialVersionUID = 1L;

public control_it () {
    super();
}

    protected void doGet(HttpServletRequest request, 
            HttpServletResponse response) 
                  throws IOException, ServletException {

        String name = "Display the name";
        request.setAttribute("name",name);

         RequestDispatcher rd=request.getRequestDispatcher("try_it.jsp");   
         rd.forward(request,response);      
   }
}