Данные пропадают при передаче между потоками с помощью Singleton - PullRequest
2 голосов
/ 19 апреля 2011

Редактировать:

Спасибо @BlackFrog.Я думаю, что сейчас я ближе, но значения все еще не проходят ...

Значения установлены, как показано в журналах в [progressController updateProgressSummary: ...], но равны нулю, когда я их регистрируюin progressUpdate initWithProgressUpdate: .... как показано ниже.

Я немного сбит с толку тем, какое свойство используется: одно установлено для progressUpdate или одно для каждого из 3 компонентов progressUpdate.Я изменил 3 отдельных свойства с назначить на сохранение, как предложено, а также попытался сделать то же самое с общим свойством progressUpdate (не показано здесь).

progressController.h

......

    @property (nonatomic, assign)   ProgressUpdate  *progressUpdate;

progressController.m

// Ask delegate to update and display Progress text
-(void) updateProgressSummary:(NSString *)summary detail:(NSString *)detail percentComplete:(NSNumber *)complete {
// These report the proper values
    DLog(@"Reporting Summary - %s", [summary UTF8String]);
    DLog(@"Reporting Detail -  %s", [detail UTF8String]);
    DLog(@"Reporting Complete -  %i", [complete intValue]); 

    if (summary != nil)
        self.progressUpdate.summaryText = summary;
    self.progressUpdate.detailText = detail;
    self.progressUpdate.percentComplete = complete;

    ProgressUpdate *progressUpdateForIssue = [[ProgressUpdate alloc] initWithProgressUpdate:progressUpdate];    
    [self.delegate performSelectorOnMainThread:@selector(displayProgress:) withObject:progressUpdateForIssue waitUntilDone:NO]; 

    [progressUpdateForIssue release];

}

Но потом, через несколько миллисекунд ... внутри объекта ... они равны нулю.

progressUpdate.h

.....

@property (nonatomic, retain) NSString  *summaryText;
@property (nonatomic, retain) NSString  *detailText;
@property (nonatomic, retain) NSNumber  *percentComplete;

progressUpdate.m

-(id) initWithProgressUpdate:(ProgressUpdate *)update {
    if ((self = [super init])) {
        summaryText = [update.summaryText copy];
        detailText = [update.detailText copy];
        percentComplete = [[NSNumber alloc] initWithFloat:[update.percentComplete floatValue]];
    }
    // These report nil values
    DLog(@"Reporting in progUpdate summaryText - %s", [summaryText UTF8String]);
    DLog(@"Reporting in progUpdate detailText -  %s", [detailText UTF8String]);
    DLog(@"Reporting in progUpdate percentComplete -  %i", [percentComplete intValue]);
return self;
}

конец обновления

Мне нужна помощь с передачей данных в пользовательском классе из одного потока в другой.Его там до перевала, но затем исчезает по прибытии.Я перепробовал все, что знаю, но безрезультатно.

Мой фоновый поток вызывает ProgressController и передает ему сведения о текущем прогрессе.Это, в свою очередь, выполняет executeSelectorOnMainThread для делегата ProgressController (контроллера представления) для отображения подробностей.

Все работало нормально, когда я проходил через одну строку NSString, но мне нужно передать две строки и число и какexecuteSelectorOnMainThread может передавать только один объект, я инкапсулировал их в пользовательский объект - ProgressUpdate.

Данные правильно попадают в ProgressController, но к моменту их появления в контроллере представления становятся нулевыми.Я знаю это, поскольку помещал NSLogs в разные места.

Интересно, имеет ли это отношение к:

  • многопоточность и пользовательские объекты

  • тот факт, что ProgressController является синглтоном, поэтому я выделяю новый ProgressUpdate каждый раз, когда он вызывается, но это не помогло.

Любые идеиДобро пожаловать.Для ясности код приведен ниже.

ProgressUpdate.h

#import <Foundation/Foundation.h>


@interface ProgressUpdate : NSObject {
    NSString    *summaryText;    
    NSString    *detailText;
    NSNumber    *percentComplete;
}
@property (nonatomic, assign) NSString  *summaryText;
@property (nonatomic, assign) NSString  *detailText;
@property (nonatomic, assign) NSNumber  *percentComplete;

-(id) initWith:(ProgressUpdate *)update;

@end

ProgressUpdate.m

#import "ProgressUpdate.h"

@implementation ProgressUpdate

@synthesize summaryText, detailText, percentComplete;

-(id) initWith:(ProgressUpdate *)update {
    self = [super init];

    self.summaryText = update.summaryText;
    self.detailText = update.detailText;
    self.percentComplete = update.percentComplete;
    return self;
}

@end

ProgressController.m

static ProgressController *sharedInstance;

+ (ProgressController *)sharedInstance {
    @synchronized(self) {
        if (!sharedInstance)
            [[ProgressController alloc] init];              
    }
    return sharedInstance;
}

+(id)alloc {
    @synchronized(self) {
        NSAssert(sharedInstance == nil, NSLocalizedString(@"Attempted to allocate a second instance of a singleton ProgressController.", @"Attempted to allocate a second instance of a singleton ProgressController."));
        sharedInstance = [super alloc];
    }
    return sharedInstance;
}
-(id) init {
    if (self = [super init]) {
        [self open];
    }
    return self;
}

.........

// Ask delegate to update and display Progress text
-(void) updateProgressSummary:(NSString *)summary detail:(NSString *)detail percentComplete:(NSNumber *)complete {

    if (summary != nil)
        self.progressUpdate.summaryText = summary;
    self.progressUpdate.detailText = detail;
    self.progressUpdate.percentComplete = complete;
    ProgressUpdate *progressUpdateForIssue = [[ProgressUpdate alloc] initWith:progressUpdate];  
    [self.delegate performSelectorOnMainThread:@selector(displayProgress:) withObject:progressUpdateForIssue waitUntilDone:NO]; 
    [progressUpdateForIssue release];

}

RootViewController.m

// Delegate method to display specific text in Progress label
- (void) displayProgress:(ProgressUpdate *)update {
    [progressSummaryLabel setText:update.summaryText];
    [progressDetailLabel setText:update.detailText];
    [progressBar setProgress:[update.percentComplete intValue]];
    [progressView setNeedsDisplay];
}

Ответы [ 2 ]

2 голосов
/ 20 апреля 2011

В методе init вы только назначаете ивары и не сохраняете их в новом объекте. Повторите ваш метод инициализации следующим образом:

-(id) initWithProgressUpdate:(ProgressUpdate *)update {
    if ((self = [super init])) {
        summaryText = [update.summaryText copy];
        detailText = [update.detailText copy];
        percentComplete = [[NSNumber alloc] initWithFloat:[update.percentComplete floatValue];
    }
    return self;
}

Пара баллов:

  • Вы не должны использовать аксессор в методе init
  • Переименуйте ваш метод инициализации, чтобы он был понятен
  • В @property измените присвоение для сохранения
0 голосов
/ 19 апреля 2011

Попробуйте удалить оператор '[progressUpdateForIssue release];' в методе

'- (void) updateProgressSummary: (NSString *) сводная информация: (NSString *) подробная информация процентComplete: (NSNumber *) выполнено'.

Также измените атрибут свойства с «назначить» на «сохранить» в вашем классе ProgressUpdate. Вы можете освободить эти свойства в методе dealloc.

Удачи.

...