Re: [問題] 關於iphone程式的問題

看板MacDev作者 (zonble)時間15年前 (2010/07/03 14:40), 編輯推噓2(203)
留言5則, 1人參與, 最新討論串4/5 (看更多)
※ 引述《wudidog (嗚啦啦)》之銘言: 整個程式問題很多…。 : FILE: A.h : @interface A : UIView <UIScrollViewDelegate> { : B *m_B; : int m_tag; 建議使用 NSIntegfer : } : @end : FILE: A.m : @implement 這一行應該是 @implementation A : -(void)addToSubview:(UIImageView*)imageview : loadImage:(NSString*)file { : UIImage *pic = [UIImage imageNamed:file]; : [imageview initWithImage:pic]; 把 alloc 與 init 放在兩個地方很不好。 : [imageview setFrame:CGRectMake( 0, 0, 300, 50)]; : [m_dic setObject:[NSNumber numberWithInt:m_tag] forKey:@"time"]; A.h 裡頭根本就沒有 m_dic 不是嗎? : imageview.tag = m_tag; : [self addSubview: imageview]; : m_tag++; : } : -(id)init { : m_b = [[B alloc] init]; m_b 產生之後也沒用到,m_b 的用途到底是? : m_tag = 50; : UIImageView *test = [UIImageView alloc]; : [self addToSubview:test loadImage:@"a.jpg"]; init 的時候需要先呼叫 [super init] 並且回傳 self 吧? : } : -(void)test { : [m_b setTime]; : } : @end : ------ : FILE: B.h : @interface B : UIImageView { : NSMutableDictionary *m_dic; : NSTimer *m_timer; : } : -(void)setTime; : @end : FILE: B.m : @implement : -(id)init { : [m_dic dictionary]; 一樣,init 應該呼叫 [super init] 並回傳 self。 而且這一行的根本問題是,我猜想你想要在這邊產生 m_dic 物件 但是你應該寫成 m_dic = [[NSMutableDictionary alloc] init]; dictionary 是 NSDictionary class 的 class method,用來產生 一個 autorelase 的 NSDictionary 物件,不是 instance method : } : -(void)change:(NSTimer *)timer { : NSLog(@"Change"); : //這行開始,「只要用到m_dic」,就會出錯 ----- : NSLog(@"%@", [m_dic count]); 要用 NSLog 看整數,要用 NSLog(@"%d", [m_dic count]); : NSNumber *digit = [m_dic objectForKey:@"time"]; : //------------------------------------------- : UIImageView *view = (UIImageView*)[self viewWithTag:digit]; : CGRect rect = [view frame]; : rect.size.width -= 50; : [view setFrame:rect]; : NSLog(@"end"); : } : -(void)setTime { : NSLog(@"setTime"); : /*----測試用,結果是正常的-------- : NSString *key = [NSString stringWithString:@"time"]; 直接寫 NSString *key = @"time" 不就好了? : NSNumber *digit = [m_dic objectForKey:key]; : NSLog(@"%@", digit); 用 NSLog(@"%@", [digit description]); 比較保險。 : --------------------------------*/ : m_timer = [NSTimer scheduledTimerWithTimeInterval:1.0 : target:self : selector:@selector(change:) : userInfo:nil : repeats:YES]; : } : @end : 大致上的code是這樣 : 有些variabe name太長或明顯無關的code : 都拿掉了 : 有用到的code就只有這樣 : method執行的順序是 : [[A alloc] init]; : [A test]; : 結果console顯示 : 在要執行m_dic那段code時 : Program received signal: “EXC_BAD_ACCESS” 遇到這種狀況,先去檢查是哪個變數指到了錯誤的指標。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.42.191.147

07/03 17:01, , 1F
感恩!請受小弟一拜 m(__)m
07/03 17:01, 1F

07/03 17:11, , 2F
回z大,確定是NSMutableDictionary的問題了!
07/03 17:11, 2F

07/03 17:13, , 3F
這部份小弟一直以用dictionary,不是用alloc和init
07/03 17:13, 3F

07/03 17:14, , 4F
改正後,程式以經正常了!
07/03 17:14, 4F

07/03 17:16, , 5F
其他z大的建議,小弟會好好研究的,有疑問再來問您!
07/03 17:16, 5F
文章代碼(AID): #1CBjjh58 (MacDev)
文章代碼(AID): #1CBjjh58 (MacDev)