您的位置:首页 > 移动开发 > Objective-C

Objective-C 学习笔记 09 - 第一个iOS应用程序

2015-01-31 11:27 260 查看
这一节我们创建一个名为iTahDoodle的iOS应用程序,这是一个简单的任务管理程序,通过property list文件保存数据。

创建iTahDoodle

新建Empty iOS应用程序工程。如下图所示通过storyboard创建主界面。



AppDelegate.h,声明辅助函数,声明用于存放task的数组,添加task函数和三个UI控件(text field,insert button和table view),最后声明自己遵循<UITableViewDataSource>协议。

#import <UIKit/UIKit.h>

// 声明辅助函数,用于返回特定文件的路径,该文件用于保存用户的任务列表信息
NSString *docPath(void);

@interface ViewController : UIViewController <UITableViewDataSource>
{
NSMutableArray *tasks;
}
- (void)addTask:(id)sender;

@end


修改AppDelegate.m

打开辅助编辑器,添加text field,button和tableView的outlet

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *taskField;
@property (weak, nonatomic) IBOutlet UIButton *insertButton;
@property (weak, nonatomic) IBOutlet UITableView *taskTable;

@end
实现辅助函数docPath

NSString *docPath()
{
NSArray *pathList = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

return [[pathList objectAtIndex:0] stringByAppendingPathComponent:@"data.td"];
}
实现UITableViewDataSource协议的必需方法

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *c = [[self taskTable] dequeueReusableCellWithIdentifier:@"Cell"];

if (!c)
{
c = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
}

NSString *item = [tasks objectAtIndex:[indexPath row]];
[[c textLabel] setText:item];

return c;
}


在viewDidLoad方法中读取plist并刷新table view

- (void)viewDidLoad {
[super viewDidLoad];

NSArray *plist = [NSArray arrayWithContentsOfFile:docPath()];
if (plist) {
tasks = [plist mutableCopy];
} else {
tasks = [[NSMutableArray alloc] init];
}

if ([tasks count] == 0)
{
[tasks addObject:@"Walk the dogs"];
[tasks addObject:@"Feed the hogs"];
[tasks addObject:@"Chop the logs"];
}

[[self taskTable] setDataSource:self];
[[self taskTable] reloadData];

}


实现addTask方法,读取text field中的字符串添加到tasks数组中,并写入plist文件

- (void)addTask:(id)sender
{
NSString *t = [[self taskField] text];

if ([t isEqualToString:@""])
{
return;
}

[tasks addObject:t];
[[self taskTable] reloadData];
[[self taskField] setText:@""];
[[self taskField] resignFirstResponder];

[tasks writeToFile:docPath() atomically:YES];
}


程序执行效果如下:



在使用辅助编辑器生成outlet过程中遇到了这样的警告Autosynthesized property 'taskField' will use synthesized instance variable '_taskField', not existing instance variable 'taskField'.

使用辅助编辑器生成outlet后,不需要再手动声明这些变量。只是注意在引用这些变量时,要使用self或者用_taskField方式来引用它们。Apple推荐的是使用self方式来引用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: