달력

7

« 2019/7 »

  •  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  •  
  •  
  •  

'Mobile DEV'에 해당되는 글 1

  1. 2013.07.08 Delegate 연습중
2013.07.08 00:32

Delegate 연습중 Mobile DEV/XCode2013.07.08 00:32


testProduct.zip


1. 새 프로젝트 생성 -> empty application-> testProduct 명으로 생성( use core data 체크, arc 미체크, 유닛 테스트 미체크 )


2. 클래스 폴더 생성 -> new file -> objective-C class 선택 -> subclass of 를 UIViewController로 선택, 클래스명은 testProductViewController 으로 하고 with Xib for user interface 체크


3. testProductViewController viewController에 관련된 파일이 3개가 생성됨 (.h, .m, .xib 파일)


4. 첫번째로해야 될 것은 새로 생성 된 viewController 를 연결 시키는 작업이 필요하다.( 기본 파일에서 수정 된 부분은 파란색으로 표기 됨 )


//testProductAppDelegate.h

#import <UIKit/UIKit.h>

#import "testProductViewController.h"


@interface testProductAppDelegate : UIResponder <UIApplicationDelegate>

{

    testProductViewController *viewController;

}


@property (strong, nonatomic) UIWindow *window;


@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;

@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;

@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;


- (void)saveContext;

- (NSURL *)applicationDocumentsDirectory;


@end



//testProductAppDelegate.m

#import "testProductAppDelegate.h"

#import "testProductViewController.h"


@implementation testProductAppDelegate


- (void)dealloc

{

    [viewController release];

    [_window release];

    [_managedObjectContext release];

    [_managedObjectModel release];

    [_persistentStoreCoordinator release];

    [super dealloc];

}


@synthesize managedObjectContext = _managedObjectContext;

@synthesize managedObjectModel = _managedObjectModel;

@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

    // Override point for customization after application launch.

    self.window.backgroundColor = [UIColor whiteColor];

    

    testProductViewController *viewController = [[testProductViewController alloc]init];

    [self.window addSubview:viewController.view];

    

    [self.window makeKeyAndVisible];

    return YES;

}


- (void)applicationWillResignActive:(UIApplication *)application

{

    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.

    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

}


- (void)applicationDidEnterBackground:(UIApplication *)application

{

    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 

    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

}


- (void)applicationWillEnterForeground:(UIApplication *)application

{

    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.

}


- (void)applicationDidBecomeActive:(UIApplication *)application

{

    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

}


- (void)applicationWillTerminate:(UIApplication *)application

{

    // Saves changes in the application's managed object context before the application terminates.

    [self saveContext];

}


- (void)saveContext

{

    NSError *error = nil;

    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;

    if (managedObjectContext != nil) {

        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {

             // Replace this implementation with code to handle the error appropriately.

             // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 

            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

            abort();

        } 

    }

}


#pragma mark - Core Data stack


// Returns the managed object context for the application.

// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.

- (NSManagedObjectContext *)managedObjectContext

{

    if (_managedObjectContext != nil) {

        return _managedObjectContext;

    }

    

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];

    if (coordinator != nil) {

        _managedObjectContext = [[NSManagedObjectContext alloc] init];

        [_managedObjectContext setPersistentStoreCoordinator:coordinator];

    }

    return _managedObjectContext;

}


// Returns the managed object model for the application.

// If the model doesn't already exist, it is created from the application's model.

- (NSManagedObjectModel *)managedObjectModel

{

    if (_managedObjectModel != nil) {

        return _managedObjectModel;

    }

    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"testProduct" withExtension:@"momd"];

    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

    return _managedObjectModel;

}


// Returns the persistent store coordinator for the application.

// If the coordinator doesn't already exist, it is created and the application's store added to it.

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator

{

    if (_persistentStoreCoordinator != nil) {

        return _persistentStoreCoordinator;

    }

    

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"testProduct.sqlite"];

    

    NSError *error = nil;

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

        /*

         Replace this implementation with code to handle the error appropriately.

         

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 

         

         Typical reasons for an error here include:

         * The persistent store is not accessible;

         * The schema for the persistent store is incompatible with current managed object model.

         Check the error message to determine what the actual problem was.

         

         

         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

         

         If you encounter schema incompatibility errors during development, you can reduce their frequency by:

         * Simply deleting the existing store:

         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

         

         * Performing automatic lightweight migration by passing the following dictionary as the options parameter:

         @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}

         

         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.

         

         */

        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

        abort();

    }    

    

    return _persistentStoreCoordinator;

}


#pragma mark - Application's Documents directory


// Returns the URL to the application's Documents directory.

- (NSURL *)applicationDocumentsDirectory

{

    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

}


@end

    


5. 이제 Delegate를 사용해 보자.

우선 testProductViewController.xib 파일을 선택하여, TextFiled 를 추가하자.

( 기본 파일에서 수정 된 부분은 파란색으로 표기 됨 )

아래 소스는 TextField가 수정되면 로그를 Delegate를 통해 남기는 코드이다.


//testProductViewController.h

#import <UIKit/UIKit.h>


@protocol testProductViewControllerDelegate;


@interface testProductViewController : UIViewController

{

    UITextField *testProuductTextField;

    id <testProductViewControllerDelegate> delegate;

}

@property (nonatomic,assign) id<testProductViewControllerDelegate> delegate;


@end




//testProductViewController.m

#import "testProductViewController.h"


@interface testProductViewController ()


@end


@implementation testProductViewController

@synthesize delegate;



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.

    

    //testProuductTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, 300, 25)];

    

//testProuductTextField.borderStyle = UITextBorderStyleRoundedRect;

    

//[self.view addSubview:testProuductTextField];

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


- (void)textFieldDidBeginEditing:(UITextField *)textField

{

    NSLog(@"textField Edit Start!");

}


-(void)dealloc

{

    NSLog(@"deAlloc");

    [super dealloc];

}


@end

'Mobile DEV > XCode' 카테고리의 다른 글

Delegate 연습중  (0) 2013.07.08
Posted by 현자