Doubles - назначить, сохранить, переписать? - PullRequest
0 голосов
/ 25 июля 2011

Я анализирую документ XML, содержащий широту / долготу, в пользовательские объекты DTO. Когда я пытаюсь установить метку из двойного значения, я получаю сообщение об ошибке, но регистрация в консоли работает. Я убежден, что это проблема памяти. У меня есть этот код:

@interface LocationResult : NSObject {
    LoginResultType result;
    LocationInfo *location;
}
@property (nonatomic, readwrite) LoginResultType result;
@property (nonatomic, retain) LocationInfo *location;

@end

@interface LocationInfo : NSObject {
    LatLng *location;
    NSString *niceLocation;
}

@property (nonatomic, retain) LatLng *location;
@property (nonatomic, retain) NSString *niceLocation;

-(LocationInfo *)initWithLocation:(NSString *)strNiceLocation latitudeIs:(double)latitude longitudeIs:(double)lonitude withPostCode:(NSString *)postCode;

@end

@interface LatLng : NSObject {
    NSString *postCode;
    double latitude;
    double longitude;
}

@property (nonatomic, retain) NSString *postCode;
@property (nonatomic, readwrite) double latitude;
@property (nonatomic, readwrite) double longitude;

-(LatLng*)initWithLocation:(NSString *)strPostCode latitudeIs:(double)latitude longitudeIs:(double)longitude;

@end

Чтобы инициализировать объект, я анализирую документ XML с использованием TouchXML:

    NSString *postCode =[[eleData nodeForXPath:@"Location/PostCode" error:nil] stringValue];
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [formatter setGeneratesDecimalNumbers:TRUE];
    NSString *rawLat =[ [eleData nodeForXPath:@"Location/Latitude" error:nil] stringValue]; 
    double lat = [rawLat doubleValue];
    NSString *rawLng = [[eleData nodeForXPath:@"Location/Longitude" error:nil] stringValue];
    double lng = [rawLng doubleValue];
    [info initWithLocation:prettyLocation latitudeIs:lat longitudeIs:lng withPostCode:postCode];
    NSLog([NSString stringWithFormat:@"%f", lat]); // works
    NSLog(info.location.postCode); // works
    NSLog([NSString stringWithFormat:@"%f", info.location.latitude]); // works

Для отображения данных:

lblCurrentPostcode.text = result.location.location.postCode;
NSLog([NSString stringWithFormat:@"%d, %d", result.location.location.latitude, result.location.location.longitude]); // this works
lblCoords.text = [NSString stringWithFormat:@"%@, %@", result.location.location.latitude, result.location.location.longitude]; // message sent to deallocated instance exception, crashes app
lblCoords.text = [NSString stringWithFormat:@"%f, %f", result.location.location.latitude, result.location.location.longitude]; // message sent to deallocated instance exception, crashes app

Я не понимаю, почему я могу войти в консоль и установить текст PostCode (NSString *), но не установить текст для координат.

Ответы [ 2 ]

0 голосов
/ 25 июля 2011

Кажется, что ярлык lblCoords был освобожден, поскольку в сообщении говорится:

сообщение отправлено исключению освобожденного экземпляра

при попытке использовать сеттер для text. Проверьте, как вы управляете этим ярлыком. double тип не является типом объекта, и нет необходимости заботиться об управлении памятью для них (это также верно для других базовых типов, таких как int, ...).

0 голосов
/ 25 июля 2011

Подключите lblCords с помощью построителя интерфейса или

lblCoords = [[UILabel alloc] init];

lblCoords.text = [NSString stringWithFormat:@"%@, %@", result.location.location.latitude, result.location.location.longitude];  
lblCoords.text = [NSString stringWithFormat:@"%f, %f", result.location.location.latitude, result.location.location.longitude];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...