为什么我的 NSMutableArray 子类没有按预期工作? [英] Why doesn’t my NSMutableArray subclass work as expected?

查看:89
本文介绍了为什么我的 NSMutableArray 子类没有按预期工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 NSMutableArray 子类化如下:

I have subclassed NSMutableArray as follows:

基类:

@interface MyBaseMutableArray : NSMutableArray {
    // Database variables
    NSString * databaseName;
    NSString * databasePath;
}

@property (nonatomic, retain) NSString * databasePath;

- (id)initWithContentsOfSQLiteDB:(NSString *)dbTable;
-(void) checkAndCreateDatabase;
-(void) readFromDatabase;

@end

子类:

@interface IngredientsMutableArray : MyBaseMutableArray
{

}

-(void) readFromDatabase;

@end

当我创建一个成分可变数组时,我执行以下操作:

When I create an IngredientsMutableArray I do the following:

IngredientsMutableArray * i  = [[IngredientsMutableArray alloc]
    initWithContentsOfSQLiteDB:@"MyIngredientsDB.sql"];

但是,当我尝试执行 [self addObject:ingred] 时,我抛出了如下异常:

BUT, when I try to perform the [self addObject:ingred] I throw an exception as follows:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSArray count]: method only defined for abstract class.  Define -[IngredientsMutableArray count]!'

我相信我没有正确初始化 NSMutableArray.我打算给我们 initWithCapaciity,但我不知道 SQL 调用之前的计数.我想我忽略了一些明显的东西,但作为 Objective C 的新手,我有点困惑.

I believe I am not initializing the NSMutableArray correctly. I was going to us initWithCapaciity, but I do not know the count before the SQL call. I think I am overlooking something obvious, but being somewhat of a newbie to Objective C I am slightly befuddled.

感谢任何帮助.

推荐答案

根据文档,您需要:

覆盖方法

NSMutableArray 的方法是概念上基于这些原始方法:

NSMutableArray‘s methods are conceptually based on these primitive methods:

insertObject:atIndex:

removeObjectAtIndex:

addObject:

removeLastObject

replaceObjectAtIndex:withObject:

在子类中,你必须覆盖所有这些方法,虽然你可以实现所需的功能只使用前两个(但是这个可能效率低下).你必须还覆盖了的原始方法NSArray 类.

In a subclass, you must override all these methods, although you can implement the required functionality using just the first two (however this is likely to be inefficient). You must also override the primitive methods of the NSArray class.

真正的答案是你并不真的想成为它的子类.有两种选择:

But the real answer is that you don't really want to be subclass it. There are two options:

  1. 使用类别
  2. 创建一个以 NSArray 作为成员变量的新类
  1. Use a category
  2. Create a new class that has an NSArray as a member variable

我想在这种情况下我会选择选项二.

I think I'd go for option two in this case.

一般来说,与在 C# 或 Java 中相比,您倾向于对系统类进行子类化的频率要低得多.

In general, you tend to subclass system classes much less often than you would in C# or Java.

这篇关于为什么我的 NSMutableArray 子类没有按预期工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆