iOSプログラミングとメモリ管理全般に比較的慣れていないスタッフがたくさんいます。保持カウントを示すいくつかのラベルと、それらの保持カウントをインクリメントおよびデクリメントするためのいくつかのボタンを備えたアプリを作成したいと思います。
誰かがすでにうまくいく何かを知っているか、それが私の主張を理解するようにこれを設定することについて何かアドバイスがありますか?動作するバージョンがありますが、思ったとおりに動作していないようです。
ViewController.h
#import <UIKit/UIKit.h>
@interface MemoryTestingViewController : UIViewController {
UILabel *retainCount;
UILabel *descLabel;
UIButton *addRetain;
UIButton *addRelease;
UIButton *access;
NSMutableString *myString;
}
@property (nonatomic, retain) IBOutlet UILabel *retainCount;
@property (nonatomic, retain) IBOutlet UILabel *descLabel;
@property (nonatomic, retain) IBOutlet UIButton *addRetain;
@property (nonatomic, retain) IBOutlet UIButton *addRelease;
@property (nonatomic, retain) IBOutlet UIButton *access;
@property (nonatomic, retain) NSMutableString *myString;
-(IBAction)pressedRetain:(id)sender;
-(IBAction)pressedRelease:(id)sender;
-(IBAction)pressedAccess:(id)sender;
@end
ViewController.m
-(IBAction)pressedAccess:(id)sender {
descLabel.text = @"Accessing myString, did we crash";
myString = [NSMutableString stringWithFormat:@"Accessing myString"];
retainCount.text = [NSString stringWithFormat:@"%i", [myString retainCount]];
}
-(IBAction)pressedRetain:(id)sender {
descLabel.text = @"Adding 1 to retain count for myString";
[myString retain];
retainCount.text = [NSString stringWithFormat:@"%i", [myString retainCount]];
}
-(IBAction)pressedRelease:(id)sender {
descLabel.text = @"Adding 1 release to myString";
[myString release];
retainCount.text = [NSString stringWithFormat:@"%i", [myString retainCount]];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
// init our variable string
myString = [[NSString alloc] init];
descLabel.text = @"myString retain count after alloc/init";
// fill our label with myString's retain count starting out
retainCount.text = [NSString stringWithFormat:@"%i", [myString retainCount]];
[super viewDidLoad];
}
これを実行すると問題ないように見えますが、保持ボタンを押そうとするとクラッシュします。誰かがこれを少しきれいにする方法について何かアドバイスがあれば、私はそれをいただければ幸いです。理想的には、保持カウントがゼロに達してアプリがクラッシュしたときにアクセスボタンを押してもらいたいのですが、保持カウントが1以上であれば、アクセスボタンは機能するはずです。ありがとう。