CoreMotionによる傾斜角測定

このQ&Aのポイント
  • iOS8、Xcode6の初心者の方が、iPod touchの傾斜角を画面に表示させるために、CoreMotionを使用したプログラムを作成していますが、角度計測が行われずに初期画面の状態のままです。
  • プログラムはエラーは出ていないため、原因がわからず困っています。ご教示いただけると幸いです。
  • また、iOS8とXcode6の初心者なので、説明文を分かりやすくしていただけると助かります。
回答を見る
  • ベストアンサー

CoreMotionによる傾斜角測定

ios8, xcode6 の初心者です。 iPodtouch の傾斜角を画面に表示させるのに以前は、 UIAccelerometerを使用していたところ、バージョンがアップされたのに伴い、 CoreMotion を使うようにとのメッセージに従い、テキスト本の作例を参考に下記のようなプログラムを書いたところ、エラーはでないのですが、初期画面の状態のままで、角度計測を行いません。 ご教示頂けましたら、幸いです。 宜しくお願い致します。 // ViewController.m #import "ViewController.h" #import <CoreMotion/CoreMotion.h> // 変数の型定義と初期値の設定 <省略> double xac; double yac; @interface ViewController () { //メンバ変数として宣言 @public AVAudioPlayer *audio; //モーションマネージャ CMMotionManager *motionManager; //水平、垂直方向の速度 double speedx; double speedy; //ビューの縦横、ボールの半径、跳ね返り係数 double viewWidth; double viewHeight; double ballR; double haneK; } //メソッド宣言 - (void)setupAccelerometer; - (void)startAnimation; - (void)animation:(CMAccelerometerData *)data; @end @implementation ViewController - (void)viewDidLoad { // extern angle; [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(update) userInfo:nil repeats:YES]; [super viewDidLoad]; [self setupAccelerometer]; } - (void)setupAccelerometer{ [self startAnimation]; angle = atan2(yac, xac) * - 180.0 / M_PI; // v = angle; NSString *path =[[NSBundle mainBundle] pathForResource:@"nothing" ofType:@"wav"]; jcount =jcount +1; angle_ar [jcount] = angle; self.jcount_Label.text = [NSString stringWithFormat:@"%d", jcount]; if (angle > angle_R) { angle_R = angle ;} if (angle < angle_L) { angle_L = angle ;} self.R_Label.text = [NSString stringWithFormat:@"Rmax= %d", angle_R]; self.Incl_Label.text = [NSString stringWithFormat:@"%d", angle]; self.black.transform = CGAffineTransformMakeRotation(M_PI * angle / 180); self.L_Label.text = [NSString stringWithFormat:@"Lmax= %d", angle_L]; // angle の値による、アラームの発生 <省略> } // 入門ノートから、以下コピー - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(BOOL)shouldAutorotate { return YES; } // ビューが表示されたらアニメーションをスタートする - (void)viewDidAppear:(BOOL)animated { [self startAnimation]; } // アニメーションのスタート - (void)startAnimation { //速度の初期化 speedx = 0; speedy = 0; // 画面の縦横サイズ viewWidth = self.view.bounds.size.width; viewHeight = self.view.bounds.size.height; // ballR = _ball.bounds.size.height/2; //跳ね返り係数 haneK = 0.6; // モーションマネージャを作る motionManager = [[CMMotionManager alloc] init]; // 加速度センサーの計測インターバルの設定 motionManager.accelerometerUpdateInterval = 0.1;// 10Hz // 定期的に実行するハンドラを設定 CMAccelerometerHandler handler = ^(CMAccelerometerData *data, NSError *error){ [self animation:data]; }; // 加速度センサーの利用を開始 [motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:handler]; } // 定期的に呼ばれてアニメーションを実行する - (void)animation:(CMAccelerometerData *)data { // double time = data.timestamp;// 経過時間 xac = data.acceleration.x;// X 軸: 加速度G yac = data.acceleration.y;// Y 軸: 加速度G // double accz = data.acceleration.z;// Z 軸: 加速度G } @end

質問者が選んだベストアンサー

  • ベストアンサー
回答No.2

No.1です。 すみません。 No.1回答の最後のNSTimerに関するコメントを訂正します。 タイマーオブジェクトをインスタンス変数やプロパティに保持しなくても、 タイマー起動中は内部(NSRunLoop内)でオブジェクトがキープされているので 現状のコーディングのままでちゃんとタイマーは起動されるようです。 むしろ、repeats:YESにしている場合、どこかでタイマーオブジェクトに 対してinvalidateを実行しないと、タイマーオブジェクトが解放されず メモリリークになってしまうようです。 例えば新しいSubViewControllerを生成して、そのSubViewControllerで 今回のようなコードでタイマーを起動すると、SubViewControllerを dismissViewControllerで終了してもタイマーは停止せず、 SubViewControllerも解放されなくなってしまうようです。 結局、タイマーをinvalidateするためにタイマーオブジェクトを インスタンス変数やプロパティに覚えておかないといけないということになります。 今回の場合、メインのViewControllerでタイマーを起動しており、 アプリの起動中ずっとタイマーを起動したままにする設計なら、 このままでも大丈夫です。

ima_mitsu
質問者

お礼

この度は、回答頂き、ありがとうございます。 自分でしばらく試行錯誤の末、下記のようにしたところ、希望の動作をしております。 しかし、progressbar の部分で新たな問題が生じました。 それは、新たに質問をアップさせて頂きたいと思います。 今後とも、宜しくお願い致します。 ありがとうございました。 // ViewController.m #import "ViewController.h" #import <CoreMotion/CoreMotion.h> @interface ViewController () { // 変数の型定義 省略 //メンバ変数として宣言 @public AVAudioPlayer *audio; //モーションマネージャ CMMotionManager *motionManager; } //メソッド宣言 - (void)startAnimation; - (void)animation:(CMAccelerometerData *)data; @end @implementation ViewController - (void)viewDidLoad { [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(update) userInfo:nil repeats:YES]; [super viewDidLoad]; [self startAnimation]; jcount= -1; } // 入門ノートからコピー -(BOOL)shouldAutorotate { return YES; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } // ビューが表示されたらアニメーションをスタートする - (void)viewDidAppear:(BOOL)animated { [self startAnimation]; } // アニメーションのスタート - (void)startAnimation { // モーションマネージャを作る motionManager = [[CMMotionManager alloc] init]; // 加速度センサーの計測インターバルの設定 motionManager.accelerometerUpdateInterval = 0.1;// 10Hz } - (void)animation:(CMAccelerometerData *)data { //jcount = -1; double xac = data.acceleration.x; // X 軸: 加速度G double yac = data.acceleration.y; // Y 軸: 加速度G angle = atan2(yac, xac) * - 180.0 / M_PI; NSString *path =[[NSBundle mainBundle] pathForResource:@"nothing" ofType:@"wav"]; jcount =jcount +1; angle_ar [jcount] = angle; self.jcount_Label.text = [NSString stringWithFormat:@"%d", jcount]; if (angle > angle_R) { angle_R = angle ;} if (angle < angle_L) { angle_L = angle ;} self.R_Label.text = [NSString stringWithFormat:@"Rmax= %d", angle_R]; self.Incl_Label.text = [NSString stringWithFormat:@"%d", angle]; self.black.transform = CGAffineTransformMakeRotation(M_PI * angle / 180); self.L_Label.text = [NSString stringWithFormat:@"Lmax= %d", angle_L]; // angle の値による、アラームの発生と傾斜角の表示 <省略> }

その他の回答 (1)

回答No.1

質問に書かれてあるコードをコピペして、 足りないところを適当に補って、エラーになるところを適当に削除して 実行してみたら、0.1秒毎にanimationメソッドが呼ばれて xac,yacに加速度センサの計測値がちゃんと入っていました。 なので、ちゃんと計測はできているけど、意図した表示ができてないんじゃないでしょうか? とりあえず、animationメソッド内でxac,yacを取得する箇所でところでNSLogで値を表示してみたら 計測できているかどうかはっきりすると思います。 表示の仕方がおかしいかどうか(というか、どんな表示を期待しているか)は、 このコードからはわかりませんでした。 animationメソッド内はxac,yacを更新するだけで、じゃあxac,yacの値を 使って、いつ表示を更新するつもりなのかこのコードからは見えませんでした。 NSTimerで0.1秒ごとにupdateメソッドを呼び出そうとしている処理があるので updateメソッド内で表示を更新しているのかなと想像しましたが、 そのupdateメソッドの処理が開示されてないのでわかりませんでした。 (updateメソッドがないのでNSTimerの処理は削除して検証しました。) ちなみにNSTimerでタイマー起動している処理は、その戻り値でもらった タイマーオブジェクトをインスタンス変数かプロパティに保持していないと、 すぐにオブジェクト解放され、タイマー呼び出しはされないと思いますよ。 もしかしたら、問題はそこかもしれませんね。

関連するQ&A

  • Objective-C 変数への代入エラー

    お世話になっております。 xCodeでiOSの開発をしておりますが、 以下のコンパイルエラーが発生してしまい解決方法が分かりません。 初歩的多所だと思いますが、ご教授お願い申し上げます。 xxxx.m @interface ViewController(){ @public NSString *hoge; } 略 -(void)hoge{ *hoge = [NSString stringWithFormat:@"%d",999]; } コンパイルエラー Assigning to 'NSString' from incompatible type 'id'

  • iphoneアプリの開発

    電卓アプリを作っています。 今困っているのは 1.割り算で小数点以下の計算ができない。 2.3つ以上の計算が(2×3×4のような)足し算しかできない。 3.間違えて数値を入力した場合に使うバックスペース的なボタンの作り方。 です。 どれか一つでもいいのでアドバイスいただけたらありがたいです。 #import "myViewController.h" @implementation myViewController // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. /* - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization. } return self; } */ // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; startInput = YES; currentValue = 0; } -(IBAction)numberButtonPressed:(id)sender { UIButton *b = (UIButton *)sender; if( startInput ){ // 最初の1桁目が0なら表示しない if( b.tag == 0 ) return; // 新しく表示する文字列を作成 label.text = [NSString stringWithFormat:@"%d", b.tag]; startInput = NO; } else { // すでに表示されている文字列に連結 label.text = [NSString stringWithFormat:@"%@%d", label.text, b.tag]; } NSString *path = [[NSBundle mainBundle] pathForResource:@"button5" ofType:@"wav"]; NSURL *url = [NSURL fileURLWithPath:path]; AVAudioPlayer *audio = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; [audio play]; } -(IBAction)equalButtonPressed:(id)sender { currentValue = sum; sum = sum-sum; // 直前に押された演算子で場合分け if( operation == 0 ){ currentValue += [label.text intValue]; } else if( operation == 1 ){ currentValue -= [label.text intValue]; } else if( operation ==2){ currentValue *= [label.text intValue]; } else if (operation ==3){ currentValue /= [label.text intValue]; } // 表示の更新 label.text = [NSString stringWithFormat:@"%d", currentValue]; startInput = YES; label2.text =@"="; NSString *path = [[NSBundle mainBundle] pathForResource:@"button5" ofType:@"wav"]; NSURL *url = [NSURL fileURLWithPath:path]; AVAudioPlayer *audio = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; [audio play]; } -(IBAction)opButtonPressed:(id)sender { UIButton *b = (UIButton *)sender; // 現在値の保存 if( operation == 0 ){ currentValue= [label.text intValue]; sum +=currentValue; label.text =[NSString stringWithFormat:@"%d", sum]; } // 演算の保存 operation = b.tag; startInput = YES; if( operation == 0 ){ label2.text =@"+"; } if( operation == 1 ){ label2.text =@"-"; } if( operation == 2 ){ label2.text =@"×"; } if( operation == 3 ){ label2.text =@"÷"; } NSString *path = [[NSBundle mainBundle] pathForResource:@"button5" ofType:@"wav"]; NSURL *url = [NSURL fileURLWithPath:path]; AVAudioPlayer *audio = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; [audio play]; } -(IBAction)clearButtonPressed:(id)sender { label.text = @"0"; startInput = YES; label2.text =@""; NSString *path = [[NSBundle mainBundle] pathForResource:@"button5" ofType:@"wav"]; NSURL *url = [NSURL fileURLWithPath:path]; AVAudioPlayer *audio = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; [audio play]; } /* // Override to allow orientations other than the default portrait orientation. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations. return (interfaceOrientation == UIInterfaceOrientationPortrait); } */ - (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. } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (void)dealloc { [super dealloc]; } @end

  • Objective-C for文でのインスタンス

    既出の質問と類似してますが、解決しないので質問します。 Objective-CのNSMutableArrayを使いラベルを複数個作りならべたいのですが、 変数iを使ってラベルに番号をつける方法がわかりません。 今のコードは NSMutableArray *tiles = [NSMutableArray array]; for( int i=0; i<25; i++ ){ UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0,0, tileSize,tileSize)]; label.text=[NSString stringWithFormat:@"%d",i]; [tiles addObject:label]; [self.view addSubview:label]; } です。 これを UILabel *label%d,i = [[UILabel alloc]initWithFrame:CGRectMake(0,0, tileSize,tileSize)]; のようにして、 label0、lable1、label2、label3・・・・ というように生成するにはどうしたらいいですか? Objective-C初心者です。 よろしくお願いします。

  • objective-c 描画処理について

    初心者ですが、iPhoneアプリを作成しています。 画像を並べてスクロールできるように配列で描画処理を行ないたいのですが、うまくいきません。 今のところのコードはこんな感じです↓ - (void)viewDidLoad { [super viewDidLoad]; NSMutableArray* imageList = [NSMutableArray array]; for (int i=1; i < 20; i++) { UIImage* image = [UIImage imageNamed: [NSString stringWithFormat:@"%d.jpg", i+1]]; [imageList addObject:image]; } MyImageView* imageView = [[MyImageView alloc] initWithImage:imageList]; scrollView.contentSize = imageView.bounds.size; [scrollView addSubview:imageView]; [imageView release]; } どなたか分かる方、教えて頂けますよう宜しくお願いします。

  • cocoa objective-c の return と * の意味がわかりません。

    objective-c の参考書を何冊か購入して 勉強しているのですが、本に載っていないようで ネットでもいくら探しても(探し方が悪いのか)行き当たらないので困ってしまいました。 先に進めなくなってしまいましたので教えていただきたく 投稿しました。 以下のコード(Project Builder起動直後のMyDocument.m)で return self; の return と - (NSString *)windowNibName の * です 使用法を教えていただけたら助かります。 よろしくお願いします。 #import "MyDocument.h" @implementation MyDocument - (id)init { self = [super init]; if (self) { message and return nil. } return self; } - (NSString *)windowNibName { return @"MyDocument"; } - (void)windowControllerDidLoadNib:(NSWindowController *) aController { [super windowControllerDidLoadNib:aController]; } - (NSData *)dataRepresentationOfType:(NSString *)aType { return nil; } - (BOOL)loadDataRepresentation:(NSData *)data ofType:(NSString *)aType { return YES; } @end

  • ボタンのtagの番号を値渡しする方法について

    今、xcodeでiphoneやipad用のアプリを作っています。 VIewController(VC)に30個くらいのボタンを置き、そのボタンのタグ番号に合わせて、SecondVIewContorller(SVC)で、画像がでてきて、それをタップしたら、次の画像へ移動するというようにしたいのですが、VCのボタンのタグ番号をSVCに送ろうとするところでひっかかっています。もし何かご助言が頂けたら誠に幸いです。よろしくお願いします。 以下、自分なりにつくったコードです。 <VCの実装> - (IBAction)pushBtn:(UIButton *)sender { [self performSegueWithIdentifier:@"mySegue" sender:self];} -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ if([segue.identifier isEqualToString:@"mySegue"]){ secondViewController*viewcon=segue.destinationViewController; viewcon.Number=[NSString stringWithFormat:@"%d",[sender tag]]; } これをSVCに送ってタグ番号をつけたいのですが、 以下の上から五行目のところの書き方のところでエラーがでてますが、他の書き方が わかりません。 <SVCの実装> - (void)viewDidLoad { [super viewDidLoad]; UIImage*imageDate=[UIImage imageNamed:@"%d,png",_Number]; CGRect rect=CGRectMake(0,0 ,200,200); UIImageView*imageView=[[UIImageView alloc]initWithFrame:rect]; imageView.image=imageDate; imageView.contentMode=UIViewContentModeScaleAspectFit; imageView.center=self.view.center; [self.view addSubview:imageView];} xcodeのバージョンは、5,0です。 重ね重ねよろしくお願いします。

  • SQLiteでデータをアプリから追加する方法

    ObjectiveCを用いてiPhoneアプリ製作の勉強をしています。 SQLiteを使って、データをアプリから追加したいのですが、その処理をするコードの記述方法が分かりません。 NSString *sql = @"CREATE TABLE IF NOT EXISTS members (year INTEGER PRIMARY KEY,month INTEGER,day INTEGER);"; NSString *insert_sql = @"INSERT INTO members (year,month,day) VALUES(?,?,?)”; NSString *select_sql = @"SELECT year,month,day FROM members”; 特に以上3行の処理の記述方法が分からず、自分なりに考えてこのように記述し試してみましたが storyboard上に追加したボタンを押してDataMakeメソッドを実行するときに ”EXC_BAD_ACCES”というエラーが出てしまいました。 以下にコードを晒します。 ■ViewController.h yearF,monthF,dayFをプロパティ宣言しています。 ■ViewController.m #import "ViewController.h" #import "FMDatabase.h" @interface ViewController () - (IBAction)DataMake:(id)sender; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSString *db_path = [self sqlmethod]; NSLog(@"%@",db_path); FMDatabase *db = [FMDatabase databaseWithPath:db_path]; NSString *sql = @"CREATE TABLE IF NOT EXISTS members (year INTEGER PRIMARY KEY,month INTEGER,day INTEGER);"; [db open]; [db executeUpdate:sql]; [db close]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (NSString*) sqlmethod{ NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); NSString *dir = [paths objectAtIndex:0]; return [dir stringByAppendingPathComponent:@"dayData.db"]; } - (IBAction)DataMake:(id)sender { NSString *db_path = [self sqlmethod]; FMDatabase *db = [FMDatabase databaseWithPath:db_path]; NSString *insert_sql = @"INSERT INTO members (year,month,day) VALUES(?,?,?)"; _yearF = 2014; _monthF = 3; _dayF = 23; [db open]; [db executeUpdate:insert_sql,@"%d",_yearF,@"%d",_monthF,@"%d",_dayF]; [db close]; [self dataopen]; } -(void)dataopen { NSString *db_path = [self sqlmethod]; FMDatabase *db = [FMDatabase databaseWithPath:db_path]; NSString *select_sql = @"SELECT year,month,day FROM members"; [db open]; FMResultSet *result = [db executeQuery:select_sql]; while ([result next]) { int result_year = [result intForColumn:@"year"]; NSLog(@"recodeyear[%d]",result_year); } } @end 以下のリンクを参考にし、”SQLiteを使用するためのライブラリ「libsqlite3.0.dylib」を追加”という項目までは出来ています。 http://blog.oukasoft.com/%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%A0/%E3%80%90iphone%E3%82%A2%E3%83%97%E3%83%AA%E3%80%91sqlite%E3%81%A7%E3%83%87%E3%83%BC%E3%82%BF%E3%83%99%E3%83%BC%E3%82%B9%E3%82%92%E4%BD%BF%E3%81%A3%E3%81%A6%E3%81%BF%E3%82%8B%E3%80%81fmdb%E3%80%81lita/

  • Objective-Cのエラーコードの意味

    タイトルの通りです。 エラー部分は最下部にあります。 ------------------------------------------------------------------------------------------------- // // ViewController.m // Kadai // // Created by on 2014/08/10. // Copyright (c) 2014年 saikoro. All rights reserved. // #import "ViewController.h" @interface ViewController () <UIAlertViewDelegate> @property (weak, nonatomic) IBOutlet UITextField *tfMyouji; @property (weak, nonatomic) IBOutlet UITextField *tfName; @property (weak, nonatomic) IBOutlet UILabel *Aisatsu; @end @implementation ViewController // 画面タッチ時 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ // キーボード非表示 [self.tfMyouji resignFirstResponder]; [self.tfName resignFirstResponder]; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } // [挨拶する]ボタン押下 - (IBAction)introduce:(id)sender { UIAlertView *av = [[UIAlertView alloc]initWithTitle:@"確認" message:@"挨拶しますか?" delegate:self cancelButtonTitle:@"キャンセル" otherButtonTitles:@"はい", nil]; // 表示 [av show]; } // AlertViewボタン押下 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"再確認" message:@"本当に挨拶しますか?" delegate:nil cancelButtonTitle:@"やっぱりやめときます" otherButtonTitles:@"早く!", nil]; [av show]; } // AlertViewボタンさらに押下 + (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ // 入力された名前の保持 NSString *str = self.tfMyouji.text; ←ここでエラーが出ます。なぜか「tfMyouji」が                    予測で出てきません } @end ------------------------------------------------------------------------------------------------- どなたかエラーの理由をご教授頂けないでしょうか。 以上、何卒宜しくお願い致します。

  • スクロールの上にある画像をフリックで変える方法とは

    今、画像を左右に数枚スクロールさせ、かつ、その画像を上や下にフリックすると各々、上や下に他の画像がでてきて、さらに拡大縮小もできるようなコードを書いています。 ViewContorller(以下、VC)にスクロールのメソッドを書き、 もう一つのPageView(UIScrollVIewクラスを親にもつ。以下、PV)に画像が拡大縮小するようなメソッドと上下のフリックのメソッドを書いています。 このPVの中で行う上下のフリックの操作によって、VCにあるスクロールの上に乗っている画像を変えたいのですが、色々と試したのですがその方法が一向にわかりません。もし宜しければ、ご教授ください。宜しくお願い致します。 xcodeは5.0です。 以下、スクロールとその上に画像をのせているpageがあるVC.mのコードです。 このpageにのっている画像をPVのほうのフリック操作で変更させたいと思っています。 - (void)viewDidLoad { [super viewDidLoad]; UIScrollView *scrollView = [[UIScrollView alloc] init]; scrollView.frame = self.view.bounds; scrollView.contentSize = CGSizeMake(self.view.frame.size.width * 3, self.view.frame.size.height); scrollView.pagingEnabled = YES; [self.view addSubview:scrollView]; //AppdelegateでValueというプロパティをつくり、PVでのフリック操作によってこの数値が変動したら、currentpageに反映して、それに対しての画像がでてくるようにしたいつもりです。 AppDelegate *appdelegate=(AppDelegate*)[[UIApplication sharedApplication]delegate]; currentpage=appdelegate.Value; //PageViewにて、画像をいれるメソッドをsetImageでつくっています。 for (int i=1;i<4;i++) { PageView *page = [[PageView alloc] initWithFrame:self.view.bounds]; [page setImage:[NSString stringWithFormat:@"%d.%d",currentpage,i]]; page.frame = CGRectMake( self.view.frame.size.width * (i-1), 0, self.view.frame.size.width, self.view.frame.size.height ); [scrollView addSubview:page]; }

  • UIImageView使用時のメモリ枯渇について

    現在、パラパラ漫画を制作しているXcode初心者のものです。 初歩的な質問とは思いますが、いろいろと調べても自分で解決することが出来ず困っております。 どうぞご教授下さいますようお願い申し上げます。 本がめくれるように見せるため、ViewControllerにViewを設置し、そのViewの中にUiImageを配置して画像をUiImageに読み込むように制作しております。 また、Viewの部分をUIViewAnimationTransitionCurlUpによってページがめくれるようにしております。 画像は、事前にAllPagesという配列に読み込んでおります。 self.AllPages=[NSMutableArray array]; for (int i=1; i<=TotalPageAmount; i++) { UIImage *image=[UIImage imageNamed:[NSString stringWithFormat:@"%@_%d",PrePageName,i]]; [AllPages addObject:image]; } 具体的な処理のソースと致しましては、以下の処理をタイマーによって呼び出して処理を行っております。 —————————————————————————————————————- [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDelegate:self]; [UIView setAnimationDuration:0.2]; [UIView setAnimationTransition:transition forView:self.ViewController cache:NO]; PageIndex++; self.UiImage.image = [self.AllPages objectAtIndex:PageIndex]; [UIView commitAnimations]; —————————————————————————————————————- メニューよりパラパラ漫画を数種類選べるようにしており、各漫画が200ページ(1枚の画像サイズは40kb程度)です。 これを実行すると、見れば見るほどメモリが使用されてしまいます。一度読み込んだものは、破棄されずそのままメモリに残っているように思われます。そのため、そのうちメモリワーニングが出てきてアプリが落ちてしまうという現象が起こっております。 ご教授いただくのに情報が不足している場合もあるかと存じますが、 どうぞ、ご指導くださいますようよろしくお願い申し上げます。

専門家に質問してみよう