• ベストアンサー

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'

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

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

ダメなところ。 1 @public 宣言は、ほとんど使わない 2 .m に  @interface XxxController (){ } などとかかない。 @interface () @end なら、高等テクニックでやるが 3 インスタンス変数で、メソッドと同じ名前を使わない。 4 インスタンス変数ではなく、できるだけ、@property をつかう。このとき、同名のメソッドは、アクセッサー 5 hogeが、NSStringオブジェクトへの紐をもつなら、   hoge= @"999"; 6 コンパイル時に結果が決まっているものを、[NSString stringWithFormat などとしない。  ということで、Objective-Cのテキスト的なものを読むことが必要でしょう。その際に、iOS4.x 以前のものは、ARC(Automatic Reference COunt)に対応していないので、価値ゼロです。また、iOS APIについては、 Storyboardの導入が、iOS5.0だったので、これ以前のものは、避けましょう。

RYO-88
質問者

お礼

ご回答ありがとうございます。 基本的なところがおさえられていなかったので、 今後もっと勉強したいと思います。

その他の回答 (1)

  • Tacosan
  • ベストアンサー率23% (3656/15482)
回答No.1

なぜに *hoge?

RYO-88
質問者

お礼

ご回答ありがとうございます。 この場合もアドレス指定が必要かと思っておりました。

関連するQ&A

  • 【Objective-c】rubyの__send__みたいな使い方がしたい。

    Objective-cで、rubyの__send__みたいな使い方がしたいです。 例えば以下のようなインターフェィスのクラスがあるとします。 @interface Hoge : NSObject { } - (NSString*)retA; - (NSString*)retB; @end ある条件によって、このクラスのメソッドの呼び別けたいです。 そこで以下のように書いたのですが、コンパイルが通りませんでした。 Hoge* hoge = [[Hoge alloc] init]; NSLog(@"%@",[hoge sw ? retA : retB]); rubyだとこんな感じです。 hoge.__send__(sw ? "retA" : "retB") ご指導のほど、宜しくお願いいたします。

  • objective-c 初心者です

    はじめまして。iphone アプリ開発を始めようと思い、まずは簡単なアプリからと人のまねをして時計アプリを書いております。http://www.slideshare.net/takuya0429/121216の43枚目のスライドを丸写しにしました。しかし、iPhoneシミュレーター(iphone 6.1)でシミュレーションしても真っ黒な画面が移されるだけで思うように機能しません。 なぜ機能しないかを考えられる範囲でご教授願いたい次第です。 環境はmacbook air 13inch にてXcode 4.6.3を使用しております。 以下に作成したコードを記載いたします。 // // ViewController.h // watch // // Created by motoyama kaoru on 2013/08/15. // Copyright (c) 2013年 motoyama kaoru. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @property (weak, nonatomic) IBOutlet UILabel *timeLabel; @end // // ViewController.m // watch // // Created by motoyama kaoru on 2013/08/15. // Copyright (c) 2013年 motoyama kaoru. All rights reserved. // #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(update) userInfo:nil repeats:YES]; } -(void)update{ NSDate *now = [NSDate date]; NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"HH:mm:ss"]; self.timeLabel.text = [df stringFromDate:now]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end

  • 【Objective-C】プロパテイについて

    Objectiv-Cの勉強を始めたばかりの者です。 プロパテイの機能を理解する為に以下のようなプログラムを書きました。 例1)まずは、プロパテイを使わない例です。 ーーーーーーー data.h ーーーーーーー #import <Foundation/NSObject.h> #import <Foundation/NSString.h> @interface Data : NSObject { NSString* str; } - (void)setStr:(NSString* )arg; - (NSString*)retStr; @end ーーーーーーー data.m ーーーーーーー #import "Data.h" @implementation Data - (NSString*) retStr{ return str; } - (void)setStr:(NSString*) arg{ [arg retain]; [str release]; str = arg; } @end ーーーーーーー main.m ーーーーーーー #import <stdio.h> #import "Data.h" int main(void) { Data* data = [[Data alloc] init]; [data setStr:@"aaa"]; NSLog(@"%@",[data retStr]); return 0; } 例2)次に、プロパテイを使って例1を書き換えてみました。 ーーーーーーー data.h ーーーーーーー #import <Foundation/NSObject.h> #import <Foundation/NSString.h> @interface Data : NSObject { NSString* str; } @property (retain) NSString* str; @end ーーーーーーー data.m ーーーーーーー #import "Data.h" @implementation Data @synthesize str; @end ーーーーーーー main.m ーーーーーーー #import <stdio.h> #import "Data.h" int main(void) { Data* test = [[Data alloc] init]; test.str = @"hoge"; NSLog(@"%@",test.str); return 0; } 例2を実行した結果、以下のように出力されました。 2010-02-05 22:17:50.696 data[1583:903] *** __NSAutoreleaseNoPool(): Object 0x100001068 of class NSCFString autoreleased with no pool in place - just leaking 2010-02-05 22:17:50.698 data[1583:903] hoge @propertyのオプションを(retain) ではなく、(assign)に変更すると、 2010-02-05 22:30:02.271 data[1619:903] hoge と出力されて、期待した結果が得られるのですが、なぜretainではダメなのでしょう? また、assignでも例1のようなメモリ管理は自動的に行われているのでしょうか? 以上、ご指導の程、よろしくお願いいたします。

  • 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 ------------------------------------------------------------------------------------------------- どなたかエラーの理由をご教授頂けないでしょうか。 以上、何卒宜しくお願い致します。

  • Objective-Cでのエラー

    よろしくお願いします。「Xcode5ではじめるObjective-Cプログラミング(大津真著)」という本を購入し、Objective-Cの勉強をはじめました。Objective-Cが初めてのプログラミング初心者です。 本に記載されたコードを入力しているのですが、下記でエラーが出て困っています。 何度も見なおしたのですが本との違いを見つけることができませんでした。 どこがおかしいのかお分かりの方がおられましたらどうか教えて下さい。 ●エラー more '%' conversions than data arguments が、下記の2箇所で出ます。(いずれも生年月日の前の@ に矢印がでています。) >NSLog(@"%@ 生年月日:%@, 身長:%.1fcm"), >NSLog(@"%@ 生年月日:%@, 身長:%.1fcm"), 実行すると Thread 1:EXC_BAD_ACCESS(code=EXC_1386_GPFLT) とでます。 ---------- // main.m #import <Foundation/Foundation.h> #import "Person.h" int main(int argc, const char * argv[]) { @autoreleasepool { Person *personA = [[Person alloc]init]; [personA setName:@"吉田一郎"]; NSDate *dateA = [NSDate dateWithString:@"1979-11-12 00:00:00 +0900"]; [personA setBirthday:dateA]; [personA setHeight:180.5]; NSLog(@"%@ 生年月日:%@, 身長:%.1fcm"), [personA name], [personA birthday], [personA height]; Person *personB = [[Person alloc]init]; [personB setName:@"山田太郎"]; NSDate *dateB = [NSDate dateWithString:@"1981-03-01 00:00:00 +0900"]; [personB setBirthday:dateB]; [personB setHeight:172.3]; NSLog(@"%@ 生年月日:%@, 身長:%.1fcm"), [personB name], [personB birthday], [personB height]; } return 0; } ---------- // Person.h #import <Foundation/Foundation.h> @interface Person : NSObject -(void)setName:(NSString *)name; -(NSString *)name; -(void)setBirthday:(NSDate *)birthday; -(NSDate *)birthday; -(double)height; -(void)setHeight:(double)newValue; @end ---------- // Person.m #import "Person.h" @implementation Person { NSString *_name; NSDate *_birthday; double _height; } -(void)setName:(NSString *)aName { _name = aName; } -(NSString *)name { return _name; } -(void)setBirthday:(NSDate *)aBirthday { _birthday = aBirthday; } -(NSDate *)birthday { return _birthday; } -(void)setHeight:(double)aHeight { _height = aHeight; } -(double)height { return _height; } @end

  • XcodeのObjective-Cについて

    大変初歩的な質問でお恥ずかしいのですが、最近Xcodeを初めて本で少しずつObjective-Cを勉強中の初心者です。 MainStoryboardでLabelをViewに配置した後、 「画面を表示する準備ができたときにコンソール画面に"こんにちは"と表示させるプログラムを追加」というものが載っているのですが、指示通り打ち込んでもエラーでうまくいきません。 本には「m.」ファイル上の「@implementation」の次の行に 01 - (void)viewDidLoad 02 { 03   [super viewDidLoad]; 04   NSLog(@"こんにちは"); 05 } とあり、その通りに打ち込んだのですが(以下Xcodeよりコピペ) @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSLog(@"こんにちは"); } - (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. } となり、 NSLog(@"こんにちは"); } の次の行の - (void)viewDidLoad に赤い!マークのエラーが表示されてしまいます。 初心者のため訂正方法もわからずネット検索しても解決しなかったので、 大変申し訳ないのですが教えていただきたく思います。

  • Objective-C,viewが動作しない

    IBを使わないカメラアプリを作っています。 AppDelegate.m内のapplication didFinishLaunchingメソッド内で生成したwindowとviewはコンパイルして表示確認できたのですが、viewControllerで書いたUIImagePickerViewControllerのviewが出てきません。 そもそもviewController.mのloadViewメソッドやviewDidLoadメソッドが動いていません。(メソッド内にNSLogを書いてコンパイルしてもログに出ない) viewController.h #import <UIKit/UIKit.h> @interface CameraViewController : UIViewController <UINavigationControllerDelegate,UIImagePickerControllerDelegate> { @private UIImagePickerController* _imagePicker; } @property(nonatomic,retain) UIImagePickerController *imagePicker; @end viewController.m #import "CameraViewController.h" @implementation CameraViewController @synthesize imagePicker=_imagePicker; - (void)dealloc { [super dealloc]; } #pragma mark - View lifecycle - (void)loadView { [super loadView]; //UIImagePickerControllerの作成 if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){ return; } UIImagePickerController* imagePicker; imagePicker = [[UIImagePickerController alloc] init]; [imagePicker autorelease]; imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; imagePicker.allowsEditing=NO; imagePicker.delegate = self; //imagePickerのviewを最上部に [self presentModalViewController:imagePicker animated:YES]; //シャッターを切る [self.imagePicker takePicture]; } @end viewControllerが機能しない原因としてそういった可能性が考えられるのでしょうか? あれこれ調べてみましたが煮詰まっています。よろしくお願いします

  • objective-cで困っています教えてください

    下記のようにUIViewの上にUIImageViewを配置し、そこにUIImageをUIViewContentModeScaleAspectFitで表示させています。 表示している画像タップして、座標をとりたいと考えています。 UIImageView(UIImage)上だけをタップのエリアにしたいのですが、画面全体がタップのエリアになってしまいます。また、画像のアスペクト比を維持しUIImageViewサイズに収まるように表示しているので、タップでとれたUIImageView上の座標と、画像上の座標にズレができてしまいます。UIImageViewサイズに収まるように表示された画像上の位置から元の画像の座標を取得する方法を教えてください。 #import "ViewController.h" @interface ViewController (){ UIImageView *imageView; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. CGRect rect = CGRectMake(0,20, 360, 480); imageView = [[UIImageView alloc] initWithFrame:rect]; imageView.backgroundColor = [UIColor redColor]; //画像のアスペクト比を維持しUIImageViewサイズに収まるように表示 imageView.contentMode = UIViewContentModeScaleAspectFit; UIImage *image = [UIImage imageNamed:@"hoge.png"]; [imageView setImage:image]; [self.view addSubview:imageView]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /** * タッチされたとき */ - (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { CGPoint p = [[touches anyObject] locationInView:imageView]; float x = p.x; // X座標 float y = p.y; // Y座標 NSLog(@"タップ開始 %f, %f", x, y); } @end

  • iPhoneアプリ作成時のXcodeのエラー

    はじめまして。 iPhoneのアプリ作成に挑戦しています。 Xcode4のバージョンは 4.5.1です。 【はじめてのXcode4プログラミング】という参考書でIPhoneのカメラアプリを作る章があり、写真ライブラリから選択した画像を表示できるとのことです。 しかし、XcodeでRun(実行)すると、ViewController.mの最後から4行目【UIImage *originalImage = [info objectForkey:UIImagePickerControllerOriginalImage];】が赤くなり、【No visible @interface for 'NSDictionary' declares the selector 'objectForkey'】というエラー表示がでます。 全体のコードは下記の通りです。 ネットで調べてみましたが、解決方法がわかりません。 先に進めず困っています。 どうか解決方法を教えてください。 よろしくお願い致します。 ●ViewController.h// // ViewController.h // CameraApp // #import @interface ViewController : UIViewController - (IBAction)pressCameraButton:(id)sender; @property (weak, nonatomic) IBOutlet UIImageView *imageView; @end ●ViewController.m // // ViewController.m // CameraApp // #import “ViewController.h” @interface ViewController () @end @implementation ViewController - (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)pressCameraButton:(id)sender { UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.delegate = self; picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; [[self presentViewController:picker animated:YES completion:nil];} - (void)imagePickerController:(UIImagePickerController*)Picker didFinishPickingMediaWithInfo:(NSDictionary*)info { [self dismissViewControllerAnimated:YES completion:nil]; UIImage *originalImage = [info objectForkey:UIImagePickerControllerOriginalImage]; // ↑↑ 上記の行でエラーが出ます self.imageView.image = originalImage; } @end

  • Objective-cで@"Foo"が使えない

    http://okwave.jp/qa/q6406418.htmlでNSLogが使えないと質問したものです。 結局NSLog(@"Foo")のうち@部分に問題があったので、質問を改めさせていただきました。 Ubuntu10.04+clang+gnustep環境で、@を使ってNSStringインスタンスを生成しようとすると エラーになります。 例:NSString *str = @"Foo"; // <- error! 例:NSLog(@"Foo"); // <- error! コンパイルではエラーが出ず、実行時にエラーになります。 $ clang -lobjc -lgnustep-base -I/usr/include/GNUstep -I/usr/lib/gcc/i486-linux-gnu/4.4/include -g -Wall oshiete.m -o oshiete $ ./oshiete Segmentation fault ちなみにコンパイラをgccに変更すると、コンパイルエラーになります。 $ gcc -lobjc -lgnustep-base -I/usr/include/GNUstep -I/usr/lib/gcc/i486-linux-gnu/4.4/include -g -Wall oshiete.m -o oshiete oshiete.m: In function ‘main’: oshiete.m:5: error: cannot find interface declaration for ‘NXConstantString’ @によってNSStringが作成されるのは、どのような環境が揃ったときなのでしょうか? 何か満たしていないものがあると思うのですが。 でも、これってObjective-c1.0の言語仕様ですよね? ほかの方のブログなど見てると使えるようなのですが、自分が使えない理由を 調べる方法が分からず困っています。 何かヒントを教えていただけないでしょうか。 よろしくお願いいたします。 (上記のgccコンパイルエラーは参考までに載せました。clangでの解決を目指したいです)

専門家に質問してみよう