简体   繁体   中英

Insert custom object to NSMutableArray

I am trying to insert my custom object BalanceData to NSMutableArray and I get an error:

No known class method for selector 'balnce'

My code:

- (void)insertNewObject:(id)sender
{
    if (!_balances) {
        _balances = [[NSMutableArray alloc] init];
    }
    [_balances insertObject:[BalanceData balance] atIndex:0]; // error occures here
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

MasterViewController.m top:

#import "MasterViewController.h"
#import "DetailViewController.h"
#import "BalanceData.h"

@interface MasterViewController () {
    NSMutableArray *_balances;
}
@end

@implementation MasterViewController

@synthesize balances = _balances;

How can I do it in proper way ?

You class BalanceData doesn't implement the balance methods. Calling in this way:

[BalanceData balance]

You're calling a class methods:

@implementation BalanceData
+ (id)balance
{ //implementation}

Add this class method to the BalanceData class and it will work. You should also override isEqual: and hash to use your objects in the collection classes.

Based on the code you provided and the error message, this doesn't appear to have anything to do with NSMutableArray...

The runtime is complaining that class BalanceData does not respond to a certain message.

So: are you calling the wrong method? Or are you intending to call an instance method but instead invoking it as a Class method? Or are you trying to call the Class method on purpose, but didn't put it in your .h file for other outside code to be able to see?

Try this on a line by itself:

[BalanceData balance];

I bet the runtime doesn't like that any better, demonstrating that your issue is here, not with the array interaction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM