www.91084.com

GVKun编程网logo

使用指针进行Objective-C Casting [复制](指针使用实例)

15

对于想了解使用指针进行Objective-CCasting[复制]的读者,本文将是一篇不可错过的文章,我们将详细介绍指针使用实例,并且为您提供关于angular–无法解析AuthenticationS

对于想了解使用指针进行Objective-C Casting [复制]的读者,本文将是一篇不可错过的文章,我们将详细介绍指针使用实例,并且为您提供关于angular – 无法解析AuthenticationService的所有参数:([object Object],?,[object Object])、Archiving Objective-C Objects with NSCoding、ios – Objective-C / NSObject指针与C指针进行比较、ios – 是否有编译为Objective-C或与Objective-C二进制兼容的语言 – > Objective-C的Coffeescript的有价值信息。

本文目录一览:

使用指针进行Objective-C Casting [复制](指针使用实例)

使用指针进行Objective-C Casting [复制](指针使用实例)

参见英文答案 > Objective-C and Pointers                                    3个
>             why most of the objects we create in iphone are pointers                                    1个
我是Objective-C的新手,来自Java背景.我刚刚在Objective-C中进行了转换,但我正在使用的书未能解释在转换时使用’*’/指针.以下是他们给我的例子:

myFraction = (Fraction *) fraction;

是不是特定对象的指针,所以他们有自己独特的内存位置?那么为什么我只能在引用类时使用指针?在这种情况下,分数.

谢谢,我希望这是有道理的,我知道这是一个我应该知道和理解的简单问题,但我找不到任何解释.

解决方法

*符号有多种含义(旁边乘法:):

>解除引用(跟随)指针.此代码跟随存储在pointerToInt中的指针,然后为其赋值.

(*pointerToInt) = 5;

>声明指针类型.当你写int *它意味着“引用一个整数”.

int x = 5;
int * xPtr = &x

现在,对象是一种结构,但我们只能通过指针操作它们.永远不要直接这基本上意味着,99%的时间当你看到*(并且它不是乘法:)它是第二种情况:类型声明的一部分:

> Nsstring * =指向Nsstring结构的指针(不能单独使用Nsstring)
>分数* =分数结构和分数结构的指针在分数类中描述

所以它不是“指向Fraction类的指针”,而是“指向Fraction类结构的指针”.

我会更进一步,回答你关于两个**的未来问题.您可能会看到通常使用NSError参数,这些参数定义为methodWithError:(NSError **)errorPtr.

短篇小说:int是int *,因为NSError *是NSError **.

长话:如果我们不能直接操作对象(没有指向它们),单个指针就成为声明的标准部分.现在如果我们想要间接访问该对象呢?我们用双指针!对象需要First *,第二个是间接.

NSError *error = nil; // Empty.
NSError **errorPtr = &error; // Reference to our local `error` variable.

[data writetoURL:URL options:kNilOptions error:errorPtr];
// That method uses:   (*errorPtr) = [NSError errorWith...];

NSLog(@"Error: %@",error); // Our local error is no longer empty.

我相信当你来自Java时,指针很奇怪.它们是C的一些遗产,但它们并没有以任何疯狂的方式使用.

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(或者相反)

Archiving Objective-C Objects with NSCoding

Archiving Objective-C Objects with NSCoding

For the seasoned Cocoa developer,this is a piece of cake. For newer developers,this can be a real pain,especially if you don't kNow what you're looking for. I get this question a decent amount,so I figured I'd put a quick guide together.

The Problem

You can't put just any object in a plist. This mainly gets people when they want to put something into NSUserDefaults and get an error (because NSUserDefaults archives to a plist under the hood).

Plists only support the core types: NsstringNSNumber,monospace">NSDate,monospace">NSData,monospace">NSArray,NSDictionary (and their CF buddies thanks to the toll-free bridge). The key here isNSDataYou can convert any object to NSData with the NSCoding protocol.

The Solution

There are two things you have to do: implement NSCoding and then use the archiver and unarchiver.

Implementing NSCoding

Say you have an object that looks like this:

@interface Note : NSObject {
    Nsstring *title;
    Nsstring *author;
    BOOL published;
}

@property (nonatomic, copy) Nsstring *title;
@property (nonatomic, copy) Nsstring *author;
@property (nonatomic) BOOL published;

@end
#import "Note.h"

@implementation Note

@synthesize title;
@synthesize author;
@synthesize published;

- (void)dealloc {
    [title release];
    [author release];
    [super dealloc];
}

@end

Pretty simple,right?

Now,all you have to do to implement NSCoding is the following:

NSObject <NSCoding> {
    Nsstring *title;
    Nsstring *author;
    dealloc {
    [title release];
    [author release];
    [super dealloc];
}

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        self.title = [decoder decodeObjectForKey:@"title"];
        self.author = [decoder decodeObjectForKey:@"author"];
        self.published = [decoder decodeBoolForKey:@"published"];
    }
    return self;
}

- (encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:title forKey:@"time"];
    [encoder encodeObject:author forKey:@"author"];
    [encoder encodeBool:published forKey:@"published"];
}

@end

Pretty simple. All I did was add the <NSCoding> protocol delectation in the header file and initWithCoder: and encodeWithCoder: in the implementation. You use these methods to tell NSCoder how to encode your object into data. Notice how two of the variables are objects and one was a BOOL. You have to use different methods for non-objects. The NSCoder documentation has the full list.

Remember,that you can use NSCoder to archive your object however whatever you want. It doesn't have to just be all of the instance variables in your object,although that's what you'll do 90% of the time.

Using the Archiver and Unarchiver

This part is also really easy. Let's say you have an array of notes that you want to put into NSUserDefaults,here's the code:

// Given `notes` contains an array of Note objects
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:notes];
[[NSUserDefaults standardUserDefaults] setobject:data forKey:@"notes"];

Unarchiving is just as easy:

NSData *notesData = [[NSUserDefaults standardUserDefaults] objectForKey:@"notes"];
NSArray *notes = [NSKeyedUnarchiver unarchiveObjectWithData:notesData];

ios – Objective-C / NSObject指针与C指针进行比较

ios – Objective-C / NSObject指针与C指针进行比较

根据apple objective-c文档,NSObject使用C指针来跟踪它们.我对iOS很新,并且将NSObjects上的指针操作与C指针进行比较会让人感到困惑.
例如:

Nsstring *string1 = @"This is a string";
Nsstring *string2;
string2 = string 1;

在C中,(如果我错了请纠正我)this = b / w 2指针使它们指向相同的“指针”.这意味着更改string1也应该更改string2.但它似乎没有像这样工作,并且Nsstrings无论如何都是严格不变的,所以这增加了一些混乱.

string1 = @"new string";

如果这些指针像C指针一样操作,那么这不应该改变string2,因为它指向与string1相同的位置.此外,在C中,必须先将指针指定给指针对象才能取消引用.此规则似乎不适用于NSObjects.什么是’@’在做什么?最后,为什么我没有看到NSObjects的解引用发生如下:

*string1 = @"modifying the string"; //shouldn't this be how to access the contents of the pointer string1 if it operates like a c pointer?

有人可以对Objective-C指针下的内容以及它们与C指针的比较和对比有所了解吗?任何帮助将不胜感激.

解决方法

您将在C中获得与Objective-C中相同的行为:如果您这样做

char *a = "hello";
char *b = a;
b = "world";

然后a不会改变.当对象可变时,对多个指针指向的公共对象所做的更改将变为可见. Nsstring和C字符串文字都不可变,所以让我们构建一个不同的例子:

NSMutableString *string1 = [NSMutableString string:@"This is a string"];
NSMutableString *string2;
string2 = string1;
NSLog(string1);
NSLog(string2);
[string1 appendString:@" (a very long one!)"];
NSLog(string1);
NSLog(string2);

现在string2“看到”对string1所做的更改,因为该对象是可变的.

C中的类似示例如下所示:

char[] a = "hello";
char b = a;
printf("%s %s\n",a,b);
strcpy(b,"world");
printf("%s %s\n",b);

ios – 是否有编译为Objective-C或与Objective-C二进制兼容的语言 – > Objective-C的Coffeescript

ios – 是否有编译为Objective-C或与Objective-C二进制兼容的语言 – > Objective-C的Coffeescript

我最近发现了 eero programming lanugage
我发现它的概念非常有趣.它似乎主要是语法糖,看起来很可读.

虽然它不直接编译到Objective-C,但它声称生成与Objective-C相同的二进制代码

Eero compiles down to the same binary code as Objective-C

Eero offers excellent,nearly seamless interoperability with
Objective-C,C,and C++.

我发现这种方法非常有趣,我想知道是否有类似的编程语言和项目提供与Objective-C和iOS的大腿集成.
我正在为Objective-C寻找类似Coffeescript的东西.

解决方法

虽然使用eero的主要方法是将其编译为本机代码,但它也支持源到源的转换(从eero到标准的Objective-C/C++).有关详细信息,请参阅 https://github.com/eerolanguage/eero/wiki/Translator.

它确实需要记录在一个更明显的地方……

今天的关于使用指针进行Objective-C Casting [复制]指针使用实例的分享已经结束,谢谢您的关注,如果想了解更多关于angular – 无法解析AuthenticationService的所有参数:([object Object],?,[object Object])、Archiving Objective-C Objects with NSCoding、ios – Objective-C / NSObject指针与C指针进行比较、ios – 是否有编译为Objective-C或与Objective-C二进制兼容的语言 – > Objective-C的Coffeescript的相关知识,请在本站进行查询。

本文标签: