GVKun编程网logo

objective-c – [__ NSArrayI replaceObjectAtIndex:withObject:]:发送到实例的无法识别的选择器

21

在这篇文章中,我们将带领您了解objective-c–[__NSArrayIreplaceObjectAtIndex:withObject:]:发送到实例的无法识别的选择器的全貌,同时,我们还将为您介

在这篇文章中,我们将带领您了解objective-c – [__ NSArrayI replaceObjectAtIndex:withObject:]:发送到实例的无法识别的选择器的全貌,同时,我们还将为您介绍有关angular – 无法解析AuthenticationService的所有参数:([object Object],?,[object Object])、ios – Objective-C – 向NSArray添加addObject、ios – Swift – 使用Objective-C选择器’*’的方法’*()’与来自超类’NSObject’的’*’的getter冲突,具有相同的Objective-C选择器、ios – [__NSArrayM objectForKeyedSubscript:]:无法识别的选择器发送到实例 – 附带源代码和截图的知识,以帮助您更好地理解这个主题。

本文目录一览:

objective-c – [__ NSArrayI replaceObjectAtIndex:withObject:]:发送到实例的无法识别的选择器

objective-c – [__ NSArrayI replaceObjectAtIndex:withObject:]:发送到实例的无法识别的选择器

我有一个NSMutableArray,我需要机会它的值,但我有这个错误:
[__NSArrayI replaceObjectAtIndex:withObject:]:无法识别的选择器发送到实例0x5291db0
这是我的NSMutableArray的声明:

NSMutableArray *selectedOptions = [NSArray arrayWithObjects:[NSNumber numberWithInteger:0],nil];

然后,我正在使用replaceObjectAtIndex方法,这样:

[self.selectedOptions replaceObjectAtIndex:0 withObject:[NSNumber numberWithInteger:1]];

但我知道,那个错误,我正在使用NSMutableArray.
谢谢

解决方法

您需要通过执行初始化NSMutableArray

NSMutableArray *selectedOptions = [NSMutableArray alloc] init];

通过使用NSArray初始化它,您不能再使用repalceObjectAtIndex:withObject:方法,这就是问题的原因.

在使用上面的行初始化NSMutableArray之后,只需使用addobject方法向其添加对象.

angular – 无法解析AuthenticationService的所有参数:([object Object],?,[object Object])

angular – 无法解析AuthenticationService的所有参数:([object Object],?,[object Object])

我遇到了下一个错误,无法理解如何解决它.

Can’t resolve all parameters for AuthenticationService: ([object Object],?,[object Object])

我已经检查了几乎每个主题,并尝试了多种方法来解决它,但仍然无法在第二天击败它.

我试图像这样在appService中注入第一个authService但是得到了同样的错误

@Inject(forwardRef(() => AuthenticationService)) public authService: AuthenticationService

我检查了所有DI和服务内部的导入顺序,在我看来一切都是正确的

如果有人可以帮我处理它,我很感激.

Angular 4.0.0

AuthService

import { Injectable } from '@angular/core';
import {Http,Headers,Response} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {Observable} from 'rxjs/Rx';

import {AppServices} from "../../app.services";
import {Router} from "@angular/router";

@Injectable()
export class AuthenticationService {
  public token: any;

  constructor(
    private http: Http,private appService: AppServices,private router: Router
  ) {
    this.token = localStorage.getItem('token');
  }

  login(username: string,password: string): Observable<boolean> {
    let headers = new Headers();
    let body = null;
    headers.append("Authorization",("Basic " + btoa(username + ':' + password)));

    return this.http.post(this.appService.api + '/login',body,{headers: headers})
      .map((response: Response) => {
        let token = response.json() && response.json().token;
        if (token) {
          this.token = token;
          localStorage.setItem('Conform_token',token);
          return true;
        } else {
          return false;
        }
      });
  }

  logout(): void {
    this.token = null;
    localStorage.removeItem('Conform_token');
    this.router.navigate(['/login']);
  }
}

应用服务

import {Injectable} from '@angular/core';
import {Headers,Http,RequestOptions} from '@angular/http';
import {Router} from "@angular/router";
import {AuthenticationService} from "./auth/auth.service";

import 'rxjs/add/operator/toPromise';
import {Observable} from 'rxjs/Rx';

@Injectable()

export class AppServices {

  api = '//endpoint/';

  public options: any;
  constructor(
    private http: Http,private router: Router,public authService: AuthenticationService // doesn't work
  //  @Inject(forwardRef(() => AuthenticationService)) public authService: AuthenticationService // doesn't work either
      ) {
        let head = new Headers({
      'Authorization': 'Bearer ' + this.authService.token,"Content-Type": "application/json; charset=utf8"
    });
    this.options = new RequestOptions({headers: head});
  }

  // ====================
  //    data services
  // ====================

  getData(): Promise<any> {
    return this.http
      .get(this.api + "/data",this.options)
      .toPromise()
      .then(response => response.json() as Array<Object>)
      .catch((err)=>{this.handleError(err);})
  }

应用模块

import { browserModule } from '@angular/platform-browser';
import { browserAnimationsModule } from '@angular/platform-browser/animations';

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import {BaseRequestOptions,HttpModule} from '@angular/http';

import { MaterialModule} from '@angular/material';
import {FlexLayoutModule} from "@angular/flex-layout";
import 'hammerjs';

import { routing,appRoutingProviders }  from './app.routing';
import { AppServices } from './app.services';
import {AuthGuard} from "./auth/auth.guard";
import {AuthenticationService} from "./auth/auth.service";

import {AppComponent} from './app.component';
import {AuthComponent} from './auth/auth.component';
import {NotFoundComponent} from './404/not-found.component';
import { HomeComponent } from './home/home.component';

@NgModule({
  declarations: [
    AppComponent,AuthComponent,NotFoundComponent,HomeComponent
  ],imports: [
    browserModule,browserAnimationsModule,FormsModule,HttpModule,routing,MaterialModule,FlexLayoutModule
  ],providers: [AppServices,AuthGuard,AuthenticationService],bootstrap: [AppComponent]
})
export class AppModule { }

解决方法

AppServices和AuthenticationService之间存在循环依赖关系 – 这与Angular使用的构造函数注入无法实现.

你可以使用

export class AuthenticationService {
  public token: any;
  appService: AppServices;
  constructor(
    private http: Http,// private appService: AppServices,injector:Injector;
    private router: Router
  ) {
    setTimeout(() => this.appService = injector.get(AppServices));
    this.token = localStorage.getItem('token');
  }

另见DI with cyclic dependency with custom HTTP and ConfigService

要避免使用setTimeout,您还可以从AppService的构造函数中设置AuthenticationService.appService(或者相反)

ios – Objective-C – 向NSArray添加addObject

ios – Objective-C – 向NSArray添加addObject

如何使用此代码将对象添加到NSArray?尝试执行此操作时出现此错误消息.

NSArray *shoppingList = @[@"Eggs",@"Milk"];
Nsstring *flour = @"Flour";
[shoppingList addobject:flour];
shoppingList += @["Baking Powder"]

错误信息

/Users/xxxxx/Documents/iOS/xxxxx/main.m:54:23: No visible @interface for 'NSArray' declares the selector 'addobject:'

请指教.谢谢.

解决方法

addobject适用于NSMutableArray,而不适用于NSArray,它是不可变的.

如果您可以控制您创建的数组,请使shoppingList NSMutableArray:

NSMutableArray *shoppingList = [@[@"Eggs",@"Milk"] mutablecopy];
[shoppingList addobject:flour]; // Works with NSMutableArray

否则,使用效率较低

shoppingList = [shoppingList arrayByAddingObject:flour]; // Makes a copy

ios – Swift – 使用Objective-C选择器’*’的方法’*()’与来自超类’NSObject’的’*’的getter冲突,具有相同的Objective-C选择器

ios – Swift – 使用Objective-C选择器’*’的方法’*()’与来自超类’NSObject’的’*’的getter冲突,具有相同的Objective-C选择器

我将此 xcode更新为6.3.1后收到此错误消息.

/Users/MNurdin/Documents/iOS/xxxxx/Models/Message.swift:46:10: Method 'hash()' with Objective-C selector 'hash' conflicts with getter for 'hash' from superclass 'NSObject' with the same Objective-C selector

我的代码

var hash_ : UInt

func hash() -> UInt {
        return UInt(hash_);
    }

请指教.谢谢.

解决方法

详细说明:@property(readonly)NSUInteger哈希是NSObject的Objective-C属性,这意味着为该变量创建了一个getter,即hash().

您现在尝试定义一个具有相同名称和相同参数(无)但具有不同返回类型的方法(UInt而不是NSUInteger,它将是swift中的Int.).因此,您收到给定的错误.要解决该问题,您现在有两个选择:

>将返回类型更改为Int – >这将覆盖预定义的哈希函数>选择其他方法名称或添加参数

ios – [__NSArrayM objectForKeyedSubscript:]:无法识别的选择器发送到实例 – 附带源代码和截图

ios – [__NSArrayM objectForKeyedSubscript:]:无法识别的选择器发送到实例 – 附带源代码和截图

在 GitHub,我有 a simple iPhone app,它从社交网络Mail.ru获取用户信息(通过使用OAuth):

它确实获取并打印信息,但随后崩溃.

作为一个iOS编程新手,我对下面的输出感到困惑(也请看the full output at PasteBin):

2014-01-21 21:21:10.873 oauthMailru[8228:3307] -[__NSArrayM objectForKeyedSubscript:]: unrecognized selector sent to instance 0x8a97290
2014-01-21 21:21:10.875 oauthMailru[8228:3307] *** Terminating app due to uncaught exception 'NSinvalidargumentexception',reason: '-[__NSArrayM objectForKeyedSubscript:]: unrecognized selector sent to instance 0x8a97290'
*** First throw call stack:
(
    0   CoreFoundation                      0x01aa65e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x018298b6 objc_exception_throw + 44
    2   CoreFoundation                      0x01b43903 -[NSObject(NSObject) doesNotRecognizeSelector:] + 275
    3   CoreFoundation                      0x01a9690b ___forwarding___ + 1019
    4   CoreFoundation                      0x01a964ee _CF_forwarding_prep_0 + 14
    5   oauthMailru                         0x00003a62 __47-[ViewController fetchMailruWithToken:ForUser:]_block_invoke + 402
    6   Foundation                          0x01545695 __67+[NSURLConnection sendAsynchronousRequest:queue:completionHandler:]_block_invoke_2 + 151
    7   Foundation                          0x014a5945 -[NSBlockOperation main] + 88
    8   Foundation                          0x014fe829 -[__NSOperationInternal _start:] + 671
    9   Foundation                          0x0147b558 -[NSOperation start] + 83
    10  Foundation                          0x01500af4 __NSOQSchedule_f + 62
    11  libdispatch.dylib                   0x021344b0 _dispatch_client_callout + 14
    12  libdispatch.dylib                   0x02121018 _dispatch_async_redirect_invoke + 202
    13  libdispatch.dylib                   0x021344b0 _dispatch_client_callout + 14
    14  libdispatch.dylib                   0x02122eeb _dispatch_root_queue_drain + 287
    15  libdispatch.dylib                   0x02123137 _dispatch_worker_thread2 + 39
    16  libsystem_pthread.dylib             0x024c0dab _pthread_wqthread + 336
    17  libsystem_pthread.dylib             0x024c4cce start_wqthread + 30
)
libc++abi.dylib: terminating with uncaught exception of type NSException

有谁请知道发生了什么以及如何阅读此类崩溃?

我的源文件:ViewController.m,显示UIWebView,然后转到DetailViewController.m

解决方法

您的代码认为JSON反序列化为对象(字典),但实际上它反序列化为包含一个对象的数组.试试这个:

NSMutableArray *topLevelArray = [NSJSONSerialization JSONObjectWithData:data
     options:NSJSONReadingMutableContainers error:nil];
 NSDictionary *dict = topLevelArray[0];

如果你想检查你得到的是什么,你可以使用isKindOfClass:像这样:

id jso = [NSJSONSerialization JSONObjectWithData:data
    options:NSJSONReadingMutableContainers error:nil];
if (jso == nil) {
    // Error.  You should probably have passed an NSError ** as the error
    // argument so you Could log it.
} else if ([jso isKindOfClass:[NSArray class]]) {
    NSArray *array = jso;
    // process array elements
} else if ([jso isKindOfClass:[NSDictionary class]]) {
    NSDictionary *dict = jso;
    // process dictionary elements
} else {
    // Shouldn't happen unless you use the NSJSONReadingallowFragments flag.
}

今天关于objective-c – [__ NSArrayI replaceObjectAtIndex:withObject:]:发送到实例的无法识别的选择器的讲解已经结束,谢谢您的阅读,如果想了解更多关于angular – 无法解析AuthenticationService的所有参数:([object Object],?,[object Object])、ios – Objective-C – 向NSArray添加addObject、ios – Swift – 使用Objective-C选择器’*’的方法’*()’与来自超类’NSObject’的’*’的getter冲突,具有相同的Objective-C选择器、ios – [__NSArrayM objectForKeyedSubscript:]:无法识别的选择器发送到实例 – 附带源代码和截图的相关知识,请在本站搜索。

本文标签: