2012-04-30 4 views
1

Получают два предупреждения «Несовместимые типы указателей с выражениями типа NSArray» в моих .m-файлах, которые я закомментировал.Несовместимые типы указателей с выражениями типа NSArray

Не понимайте это полностью и не знаете, как это исправить. Можете ли вы объяснить это, чтобы я мог это исправить?

Заранее спасибо.

ItemsViewController.m

#import "ItemsViewController.h" 
#import "BNRItemStore.h" 
#import "BNRItem.h" 

@implementation ItemsViewController // Incomplete implementation 

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    DetailViewController *detailViewController = [[DetailViewController alloc]init]; 

    NSArray *items = [[BNRItemStore sharedStore]allItems]; 
    BNRItem *selectedItem = [items objectAtIndex:[indexPath row]]; 

    //Give detail view controller a pointer to the item object in a row 
    [detailViewController setItem:selectedItem]; 

    // Push it onto the top of the navigation controller's stack 
    [[self navigationController]pushViewController:detailViewController animated:YES]; 
} 

-(id)init 
{ 
    // Call the superclass's designated initializer 
    self = [super initWithStyle:UITableViewStyleGrouped]; 
    if (self) { 


    } 
    return self; 
} 

-(id)initWithStyle:(UITableViewStyle)style 
{ 
    return [self init]; 
} 

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [[[BNRItemStore sharedStore]allItems]count]; 
} 

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 


    // Check for a reusable cell first, use that if it exists 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"]; 

    // If there is no reusable cell of this type, create a new one 
    if (!cell) { 
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"]; 
    } 

    // Set the text on the cell with the description of the item 
    // that is at the nth index of items, where n = row this cell 
    // will appear in on the tableview 
    BNRItem *p = [[[BNRItemStore sharedStore]allItems]objectAtIndex:[indexPath row]]; 

    [[cell textLabel]setText:[p description]]; 

    return cell; 
} 

-(UIView *)headerView 
{ 
    // If we haven't loaded the headerView yet 
    if (!headerView) { 
    //Load HeaderView.xib 
    [[NSBundle mainBundle]loadNibNamed:@"HeaderView" owner:self options:nil]; 
    } 
    return headerView; 
} 

-(UIView *)tableView:(UITableView *)tv viewForHeaderInSection:(NSInteger)sec 
{ 
    return [self headerView]; 
} 

-(CGFloat)tableView:(UITableView *)tv heightForHeaderInSection:(NSInteger)sec 
{ 
    // The height of the header view should be determined from the height of the 
    // view in the XIB file 
    return [[self headerView]bounds].size.height; 
} 

-(IBAction)toggleEditingMode:(id)sender 
{ 
    // If we are currently in editing mode 
    if ([self isEditing]) { 
    // Change text of button to inform user of state 
    [sender setTitle:@"Edit" forState:UIControlStateNormal]; 
    // Turn off editing mode 
    [self setEditing:NO animated:YES]; 
    } else { 
    // Change text of button to inform user of state 
    [sender setTitle:@"Done" forState:UIControlStateNormal]; 
    // Enter editing mode 
    [self setEditing:YES animated:YES]; 
    } 
} 

-(IBAction)addNewItem:(id)sender 
{ 
    // Create a new BNRItem and add it to the store 
    BNRItem *newItem = [[BNRItemStore sharedStore]createItem]; //Incompatible pointer types initializing 'BNRItem *__strong' with an expression of type 'NSArray*' 

    // Figure out where that item is in the array 
    int lastRow = [[[BNRItemStore sharedStore]allItems]indexOfObject:newItem]; 

    NSIndexPath *ip = [NSIndexPath indexPathForRow:lastRow inSection:0]; 

    // Insert this new row into the table 
    [[self tableView]insertRowsAtIndexPaths:[NSArray arrayWithObject:ip] withRowAnimation:UITableViewRowAnimationTop]; 
} 

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // If the table view is asking to commit a delete command... 
    if(editingStyle == UITableViewCellEditingStyleDelete) 
    { 
    BNRItemStore *ps = [BNRItemStore sharedStore]; 
    NSArray *items = [ps allItems]; 
    BNRItem *p = [items objectAtIndex:[indexPath row]]; 
    [ps removeItem:p]; 

    // We also remove that row from the table view with an animation 
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    } 
} 

-(void)tableView:(UITableView *)tableView 
    moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath 
     toIndexPath:(NSIndexPath *)destinationIndexPath 
{ 
    [[BNRItemStore sharedStore]moveItemAtIndex:[sourceIndexPath row] 
            toIndex:[destinationIndexPath row]]; 
} 

-(void)viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear:animated]; 
    [[self tableView] reloadData]; 
} 


@end 

ItemsViewController.h

#import <Foundation/Foundation.h> 
#import "DetailViewController.h" 

@interface ItemsViewController : UITableViewController 
{ 
    IBOutlet UIView *headerView; 
} 

-(UIView *)headerView; 
-(IBAction)addNewItem:(id)sender; 
-(IBAction)toggleEditingMode:(id)sender; 

@end 

BNRItemStore.m

#import "BNRItemStore.h" 
#import "BNRItem.h" 

@implementation BNRItemStore 

+(BNRItemStore *)sharedStore 
{ 
    static BNRItemStore *sharedStore = nil; 
    if (!sharedStore) 
    sharedStore = [[super allocWithZone:nil]init]; 

    return sharedStore; 
} 

-(id)init 
{ 
    self = [super init]; 
    if (self) { 
    allItems = [[NSMutableArray alloc]init]; 

    } 
    return self; 
} 

-(NSArray *)allItems 
{ 
    return allItems; 
} 

-(NSArray *)createItem 
{ 
    BNRItem *p = [BNRItem randomItem]; 
    [allItems addObject:p]; 
    return p; //Incompatible pointer types returning 'BNRItem*__strong' from a function with result type 'NSArray*' 
} 

-(void)removeItem:(BNRItem *)p 
{ 
    [allItems removeObjectIdenticalTo:p]; 
} 

-(void)moveItemAtIndex:(int)from 
       toIndex:(int)to 
{ 
    if(from==to) { 
    return; 
    } 
    // Get pointer to object being moved so we can re-insert it 
    BNRItem *p = [allItems objectAtIndex:from]; 

    // Remove p from array 
    [allItems removeObjectAtIndex:from]; 

    //Insert p in array at new location 
    [allItems insertObject:p atIndex:to]; 
} 

@end 

BNRItemStore.h

#import <Foundation/Foundation.h> 

@class BNRItem; 

@interface BNRItemStore : NSObject 
{ 
    NSMutableArray *allItems; 
} 

// Notice that this is a class method and prefixed with a + instead of a - 
+(BNRItemStore *)sharedStore; 

-(void)removeItem:(BNRItem *)p; 
-(void)moveItemAtIndex:(int)from 
       toIndex:(int)to; 

-(NSArray *)allItems; 
-(NSArray *)createItem; 

@end 

ответ

2

Посмотрите на тип возвращаемого метода определения метода, а затем посмотрите на тип возвращаемого var.

-(NSArray *)createItem 
{ 
    BNRItem *p = [BNRItem randomItem]; 
    [allItems addObject:p]; 
    return p; //Incompatible pointer types returning 'BNRItem*__strong' from a function with result type 'NSArray*' 
} 

Похоже, вы должны возвращаться allItems вместо p.

Или изменить тип возврата на BNRItem *.

2

В здесь:

-(NSArray *)createItem 
{ 
    BNRItem *p = [BNRItem randomItem]; 
    [allItems addObject:p]; 
    return p; //Incompatible pointer types returning 'BNRItem*__strong' from a function with result type 'NSArray*' 
} 

p является переменной типа BNRItem*. Ваш метод утверждает, что его возвращаемое значение равно NSArray*. Предупреждение объясняется тем, что оно отличается.

Если вы хотите вернуть весь массив, верните allItems.

Если вы хотите вернуть новый элемент, измените тип возврата.

+0

Да, это работает, спасибо. Но я все еще путаюсь с другим методом, потому что хочу добавить новый элемент в хранилище, который представляет собой одноэлементный массив и контейнер. Нужно ли мне давать ему слабое отношение к BNRItemStore, в то время как BNRItemStore имеет прочные отношения с BNRItem? Если да, то как мне это сделать? Спасибо. – pdenlinger

2
-(void)moveItemAtIndex:(int)from 
       toIndex:(int)to 

Этот метод будет работать как написано; если to после from, вы будете перемещать объект в неправильный индекс и, возможно, вызывать исключение вне диапазона в этом процессе.


Как и другие, ваш метод createItem объявлен как возвращающий NSArray*, но вы возвращаете BNRItem*.

Фиксация типа возврата также позволит устранить другое предупреждение.


В своем комментарии к «quixoto» вы задаете некоторые вопросы моделирования. Похоже, что вы действительно должны использовать CoreData, который явно предназначен для разрешения таких задач моделирования.

+3

OP работает через учебную книгу и еще не дошел до главы CoreData. –

Смежные вопросы