新規プロジェクトの作成
Class Prefixの命名規則
- Product Name が
MyApp
だとしたらMA
(以下MAで進めるのでよしなに変更してください)
Company Identifier
- 空だと完了できないので
edu.self
とか入れておけばいいのでは
Storyboardで面の作成
1.ViewControllerの作成
- Editor > Embed In > Navigation Controler
2.テキストフィールドの作成
- Object Libraryから「Text Field」を選択して1.に配置
3.ボタンの作成
- Object Libraryから「Round Rect Button」を選択して1.に配置
- 保存用/一覧画面遷移用に2つ作成
4.TableViewControllerの作成
- Object Libraryから「Table View Controller」を選択してstoryboard上に配置
- これがメモ一覧画面になる
5.TableViewController用のクラスを新規作成
- File > New > File > Objective-C class
- Class
MAMemoListViewController
- Subclass of
UITableViewController
6.Cellのidentifierを指定
MemoListViewControllerに定義してあるCellIdentifier名をstoryboardの対象セルに指定する
MAMemoListViewController.m
static NSString *CellIdentifier = @"Cell";
以上で下記画面とクラスが関連づけられた
* 書き込み画面 : MAViewController
* 一覧画面 : MAMemoListViewController
保存機能の作成
1.MemoListクラス作成
- Class
MAMemoList
- Subclass of
NSObject
MAMemoList.h
#import <Foundation/Foundation.h>
@interface MAMemoList : NSObject
@property (nonatomic, strong) NSMutableArray *memos;
+ (id)sharedMemoList;
@end
MAMemoList.m
#import "MAMemoList.h"
@implementation MAMemoList
+ (id)sharedMemoList {
static dispatch_once_t pred = 0;
__strong static id _sharedObject = nil;
dispatch_once(&pred, ^{
_sharedObject = [[self alloc] init];
});
return _sharedObject;
}
- (id)init {
self = [super init];
if (!self) {
return nil;
}
self.memos = [[NSMutableArray alloc] init];
return self;
}
@end
2.Memoクラス作成
- Class
MAMemo
- Subclass of
NSObject
MAMemo.h
#import <Foundation/Foundation.h>
@interface MAMemo : NSObject
@property (nonatomic, strong) NSString *title;
@end
3.保存アクションの作成
MPViewController.m
#import "MPMemoList.h"
#import "MPMemo.h"
@interface MPViewController ()
@property (weak, nonatomic) IBOutlet UITextField *memotext;
@end
- (IBAction)createMemo:(id)sender {
MPMemo *memo = [[MPMemo alloc] init];
memo.title = self.memotext.text;
[[[MPMemoList sharedMemoList] memos] addObject:memo];
}
※ property:*title
と createMemo
について、それぞれStoryboardからクラスへ定義を行わないとうまく動作しない?(storyboard上で Ctrl
押しながらクラスファイルへドラッグ)それぞれが定義されてるコードの左側に ◉
のマークが出ていれば問題なさそう。
一覧表示機能の作成
MAMemoListViewController.m
#import "MAMemoList.h"
#import "MAMemo.h"
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
// Return the number of rows in the section.
return [[[MAMemoList sharedMemoList] memos] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
cell.textLabel.text = [[[[MAMemoList sharedMemoList] memos] objectAtIndex:indexPath.row] title];
return cell;
}