使用委托清理数组

时间:2013-10-21 09:39:39

标签: ios objective-c delegation

我制作了一个识别图像的AR应用程序,并显示AlertView中识别的对象。在AlertView中,我有2个按钮:添加和取消,我正在使用UIAlertViewDelegate来了解用户按下的按钮。如果用户按下“添加”按钮,则识别的对象将存储在数组中。我将此数组传递给另一个ViewController,我在其中设置了一个TableView。在这个TableView的底部有一个按钮“Pay”转到另一个ViewController,在其中我显示被识别对象的总价。从最后一个ViewController我可以按一个按钮来支付我使用AR选择的对象。现在,当我按下此按钮时,应用程序关闭此ViewController并返回到第一个ViewController,但是我在其中存储了AR识别出它的对象的数组。要删除这个数组的内容,我认为最好的方法是使用委托方法,所以我做了这个:

PaymentViewController.h

#import <UIKit/UIKit.h>

@protocol PaymentViewControllerDelegate;

@interface PaymentViewController : UIViewController
@property (strong, nonatomic) IBOutlet UILabel *labelTotal;
- (IBAction)buttonClosePaymentVC:(id)sender;

- (IBAction)buttonPay:(id)sender;

@property(nonatomic,strong)NSString *total;

@property(assign) id<PaymentViewControllerDelegate> delegate;

@end

@protocol PaymentViewControllerDelegate <NSObject>

- (void)cleanReportArray;

@end

PaymentViewController.m

#import "PaymentViewController.h"

@interface PaymentViewController () <UIAlertViewDelegate>

@end

@implementation PaymentViewController
@synthesize delegate = _delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.labelTotal.text = self.total;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)buttonClosePaymentVC:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)buttonPay:(id)sender {
    NSString *pay = [NSString stringWithFormat:@"Stai per pagare %@, procedi?", self.total];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"HelloMS" message:pay delegate:self cancelButtonTitle:@"Si" otherButtonTitles:@"No", nil];
    [alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        // Procedura per il pagamento e cancellazione del file plist
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *path = [documentsDirectory stringByAppendingPathComponent:@"objects.plist"];
        NSError *error;
        if (![[NSFileManager defaultManager]removeItemAtPath:path error:&error]) {
            NSLog(@"Errore: %@", error);
        }
        __weak UIViewController *vcThatPresentedCurrent = self.presentingViewController;
        [self dismissViewControllerAnimated:YES completion:^{
            [vcThatPresentedCurrent dismissViewControllerAnimated:YES completion:nil];
        }];
        [self.delegate cleanReportArray];
    }
    if (buttonIndex == 1) {
        // Non deve far nulla: fa scomparire l'UIAlertView
    }
}

在这里,我向您发布将使用委托的类的方法:

ScannerViewController.m的界面

@interface ScannerViewController () <MSScannerSessionDelegate, PaymentViewControllerDelegate, UIActionSheetDelegate, UIAlertViewDelegate>
@property (weak) IBOutlet UIView *videoPreview;
- (IBAction)stopScanner:(id)sender;
@end

ViewDidLoad我插入了这些行:

PaymentViewController *pay = [[PaymentViewController alloc]init];
[pay setDelegate:self];

ScannerViewController.m我实现了我在PaymentViewController.h中声明的方法:

- (void)cleanReportArray {
    [arrayObjectAdded removeAllObjects];
}

我在我的iPhone上测试了我的应用程序,该应用程序工作正常,直到我尝试支付我通过相机扫描的对象,实际上,我试图支付对象,但它不清理我存储对象的数组扫描。 我的代码有什么问题?我在网上使用了一个教程来更好地理解委托方法的工作原理。我希望你能帮我解决这个问题,谢谢

更新 在这里,我将发布我的ScannerViewController代码:

ScannerViewController.h

#import <UIKit/UIKit.h>

@interface ScannerViewController : UIViewController

@end

ScannerViewController.m

#import "ScannerViewController.h"
#import "PaymentViewController.h"
#import "ReportViewController.h"
#import "MSScannerSession.h"
#import "MSResult.h"
#import "XmlReader.h"

static int kMSScanOptions = MS_RESULT_TYPE_IMAGE    |
                            MS_RESULT_TYPE_EAN8     |
                            MS_RESULT_TYPE_EAN13;

@interface ScannerViewController () <MSScannerSessionDelegate, PaymentViewControllerDelegate, UIActionSheetDelegate, UIAlertViewDelegate>
@property (weak) IBOutlet UIView *videoPreview;
- (IBAction)stopScanner:(id)sender;
@end

@implementation ScannerViewController {
    MSScannerSession *_scannerSession;
    NSString *nameOfObjectScanned;
    XmlReader *reader;
    NSMutableArray *arrayObjectAdded;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _scannerSession = [[MSScannerSession alloc] initWithScanner:[MSScanner sharedInstance]];
        [_scannerSession setScanOptions:kMSScanOptions];
        [_scannerSession setDelegate:self];

    }
    return self;
}

- (void)session:(MSScannerSession *)scanner didScan:(MSResult *)result {
    if (!result) {
        return;
    }
    [_scannerSession pause];

    NSString *resultStr = nil;

    if (result) {
        switch ([result getType]) {
            case MS_RESULT_TYPE_IMAGE:
                resultStr = [NSString stringWithFormat:@"Immagine trovata: %@", [result getValue]];
                break;
            case MS_RESULT_TYPE_EAN8:
            case MS_RESULT_TYPE_EAN13:
                resultStr = [NSString stringWithFormat:@"EAN trovato: %@", [result getValue]];
                break;
            default:
                break;
        }
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        UIActionSheet *asView = [[UIActionSheet alloc]initWithTitle:resultStr delegate:self cancelButtonTitle:@"OK" destructiveButtonTitle:nil otherButtonTitles:nil, nil];
        asView.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
        [asView showInView:self.view];
        [self addObjectToList:resultStr];
    });

}

- (void)addObjectToList:(NSString *)objectName {
    // Ricerca dell'oggetto
    NSString *object = [objectName substringFromIndex:18];
    if ([object isEqualToString:@"Binario_con_coppia"]) {
        [self showAlert:object];
    }
    if ([object isEqualToString:@"Dadi_colorati"]) {
        [self showAlert:object];
    }
    if ([object isEqualToString:@"Dadi_rossi"]) {
        [self showAlert:object];
    }
    if ([object isEqualToString:@"Bici_da_corsa"]) {
        [self showAlert:object];
    }
}

- (void)showAlert:(NSString*)name {
    name = [name stringByReplacingOccurrencesOfString:@"_" withString:@" "];
    nameOfObjectScanned = name;
    NSString *message = [NSString stringWithFormat:@"Ho riconosciuto questo oggetto: %@, vuoi aggiungerlo al carrello?", name];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"HelloMS" message:message delegate:self cancelButtonTitle:@"Aggiungi" otherButtonTitles:@"Annulla", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        NSLog(@"Aggiungi");
        for (int i = 0; i < [reader.objArray count]; i++) {
            if ([[reader.objArray[i]objectForKey:@"name"] isEqualToString:nameOfObjectScanned]) {
                // Salvo il nome dell'oggetto trovato, il prezzo e la descrizione
                NSString *name = [reader.objArray[i]objectForKey:@"name"];
                NSString *desc = [reader.objArray[i]objectForKey:@"desc"];
                NSString *price = [reader.objArray[i]objectForKey:@"price"];
                NSDictionary *newObjectAdded = [[NSDictionary alloc]init];
                newObjectAdded = @{@"name": name,
                                   @"desc": desc,
                                   @"price": price};
                [arrayObjectAdded addObject:newObjectAdded];
            }
        }
    } else {
        NSLog(@"Annulla");
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    [_scannerSession resume];
}


- (void)viewDidLoad
{
    [super viewDidLoad];

    arrayObjectAdded = [[NSMutableArray alloc]init];
    CALayer *videoPreviewLayer = [self.videoPreview layer];
    [videoPreviewLayer setMasksToBounds:YES];

    CALayer *captureLayer = [_scannerSession previewLayer];
    [captureLayer setFrame:[self.videoPreview bounds]];

    [videoPreviewLayer insertSublayer:captureLayer below:[[videoPreviewLayer sublayers] objectAtIndex:0]];
    reader = [[XmlReader alloc]init];
    [reader parseXml];
    [_scannerSession startCapture];
    PaymentViewController *pay = [[PaymentViewController alloc]init];
    [pay setDelegate:self];
}

- (void)cleanReportArray {
    [arrayObjectAdded removeAllObjects];
}

- (void)dealloc {
    [_scannerSession stopCapture];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)stopScanner:(id)sender {
    ReportViewController *reportVC = [[ReportViewController alloc]initWithNibName:@"ReportViewController" bundle:nil];
    reportVC.reportArray = arrayObjectAdded;
    [reportVC setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
    [self presentViewController:reportVC animated:YES completion:nil];
}

@end

要识别图片我正在使用此AR SDK。我希望你能帮助我理解我的问题在哪里

1 个答案:

答案 0 :(得分:1)

您的问题是在viewDidLoad中您有代码:

PaymentViewController *pay = [[PaymentViewController alloc]init];
[pay setDelegate:self];

这是你在该方法中做的最后一件事。因此,您创建和设置委托的PaymentViewController实例会立即销毁(通过ARC)。

您需要修改代码,以便在屏幕上显示的setDelegate:的实际实例上调用PaymentViewController,因为这是需要使用委托的实例(它接收来自的回调)警报视图)。